3

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 ?

François Richard
  • 6,111
  • 10
  • 34
  • 66

2 Answers2

2

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)());
Tushar
  • 78,625
  • 15
  • 134
  • 154
0

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).

Oooogi
  • 363
  • 4
  • 14