Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assignment and function execution [duplicate]

Tags:

javascript

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 ?

like image 928
François Richard Avatar asked Apr 27 '26 07:04

François Richard


1 Answers

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)());
like image 101
Tushar Avatar answered Apr 28 '26 19:04

Tushar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!