I'm not sure to understand why this is resulting to undefined
var foo = {
bar: function(){ return this.baz; },
baz: 1
}
console.log(typeof (f = foo.bar)());
Any idea ?
I'm not sure to understand why this is resulting to undefined
var foo = {
bar: function(){ return this.baz; },
baz: 1
}
console.log(typeof (f = foo.bar)());
Any idea ?
You need to invoke the bar
function to get the baz
var foo = {
bar: function () {
return this.baz;
},
baz: 1
};
console.log(typeof (f = foo.bar()));
This depends on how the function is called. When calling f()
the context is set to the Window
object. As there is no global variable baz
the function f
will return undefined
.
You can verify this by logging the this
inside the bar()
.
var foo = {
bar: function() {
console.log(this);
return this.baz;
},
baz: 1
}
console.log('Called on foo', typeof foo.bar());
console.log('Called as `f()`', typeof(f = foo.bar)());
To change the context of the function, you can use Function#call
or Function#apply
or Function#bind
.
var foo = {
bar: function () {
return this.baz;
},
baz: 1
};
console.log('Called as `f().call(foo)`', typeof (f = foo.bar).call(foo));
console.log('Called as `f().apply(foo)`', typeof (f = foo.bar).apply(foo));
console.log('Using bind', typeof (f = foo.bar).bind(foo)());
What were you expecting to find?
If you were expecting to get "function" as in foo.bar then you should rewrite your code like this:
var foo = {
bar: function(){ return this.baz; },
baz: 1
}
console.log(typeof (f = foo.bar));
I think you have a set of parentheses which shouldn't exists -> right after the "(f = foo.bar)" part.
But if you were trying to get the type of foo.baz then you should rewrite you code like this:
var foo = {
bar: function(){ return foo.baz; },
baz: 1
}
console.log(typeof (f = foo.bar));
"this" is undefined because it is a singletone js object, not a class (function).