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)());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With