I am writting some functions for a website and I am experiencing weird thing. I am using jQuery and Angular.js as my base frameworks. I don't know javascript very well, but I learned from some tutorials, but and I am still not sure why some things work and other doesn't.
In my code, I had the following function:
var obj;
setTimeout(() => calc(obj), 10);
obj = {a: 5};
function calc(obj){
console.log(obj.a);
}
It works as I expected. So, I have variable obj
, firstly I prepare timeout to be called in 10 milliseconds. After that, I initialize obj
to have property a
which value is 5
. So, I suppose 10 milliseconds are enough for obj
to be initialized, so calc
should print 5
. It works every time.
However, I found out that creating a new arrow function just to call calc
is bad practice. It is FASTER to pass bound function (using bind
). So, I rewrote my code like this:
var obj;
setTimeout(calc.bind(obj), 10);
obj = {a: 5};
function calc(obj){
console.log(obj.a);
}
However, now I get error
TypeError: Cannot read property 'a' of undefined
They said that bind
method is faster. However, it prints obj
is still udnefined
even after 10
miliseconds (which is enough for arrow function method). I increased setTimeout
to 1e4
miliseconds, but obj
is still undefined
. How is that even possible.
It seems like obj
is always undefined, even after 10
seconds. Why they said that bind
is fatster, but I just proved that it is a lot slover than my arrow function method.
What is actually happening here?
via omaklomisedoslodokratkogspoja
No comments:
Post a Comment