var foo = {
bar: function() { return this.baz; },
baz: 1
};
(function(){
return typeof arguments[0]();
})(foo.bar);
Why does this c
the code won't work because inside the anonymous function you lose the reference to this.baz
of foo object when used in another context
you can use the apply()
method to redefine the context, like so
var foo = {
bar: function() { return this.baz; },
baz: 1
};
(function(){
return arguments[0].apply(foo);
})(foo.bar);
and this returns correctly 1
because apply() method change the execution context to the object passed as argument
typeof arguments[0].apply(foo);
returns number
as expected