Reputation: 106
I am new to javascript, The below question should return 1 according to my knowledge about javascript, but it's returning "undefined". could anyone tell me why it's not returning 1?
var foo = {
bar: function() { return this.baz; },
baz: 1
};
(function(){
return typeof arguments[0]();
})(foo.bar);
Upvotes: 2
Views: 97
Reputation: 320
When you invoke a function with .
operator, then the object to the left of .
becomes the context of invocation, which is this
. But when you pass your function to another one as an argument, you lose the context, since you call it directly. If you want to preserve the context you can use bind
.
(function(){
return typeof arguments[0]();
})(foo.bar.bind(foo));
And, yeah, your function actually returns the type of baz
, not the value itself. Remove typeof
if you want to see 1
.
Upvotes: 5
Reputation: 817130
why its returning the “undefined” instead of 1
Because the way you call the function, this
inside foo.bar
refers to the global object (i.e. window
). There is no global variable baz
hence this.baz
(window.baz
) is undefined
.
Learn more about how this
works here:
Besides, it would never ever return 1
because typeof
returns the type of a value. 1
is not a type. At best it would return "number"
:
console.log(typeof 1);
console.log(typeof undefined);
To learn how to control the value of this
, have a look at the links above and at How to access the correct `this` context inside a callback? .
Upvotes: 1