Unfortunately .bind
has been giving me grief when creating more complex closures.
I am quite interested in why .bind seems to work differently once you nest functions.
For example :
function t(){
t = t.bind({}); //correctly assigns *this* to t
function nested_t(){
nested_t = nested_t.bind({}); // fails to assign *this* to nested_t
return nested_t;
}
return nested_t();
}
//CASE ONE
alert(t());
// alerts the whole function t instead of nested_t
//CASE TWO
aleft(t.call(t));
// alerts the global object (window)
In both cases I was expecting a behavior like this:
function t(){
var nested_t = function nested_t(){
return this;
};
return nested_t.call(nested_t);
}
alert(t.call(t));
If someone could explain the behavior of .bind
in the first (and/or) second case it would be much appreciated!
So, i'm not entirely reproducing your issue here (both cases return the global object), but i'll try and explain the code as i see it.
Let's take it step by step.
First, the function
t()
is defined. Then, upon call, it gets overwritten with a clean context. However, i don't see any usage of this context.Now, a nested function (
nested_t
) is defined. Upon call, it is overwritten with a clean context. It then returns the context it had when it was called.Back to
t()
. You then return the result ofnested_t()
, notnested_t
itself. In the original function call,nested_t
is still being called with global context.Therefore, when you run
t()
, it returns the global object.