2

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);
Alberto
  • 1,106
  • 15
  • 29
messi
  • 108
  • 8
  • 1
    Because `this` inside `foo.bar` refers to the global object. There is no global variable `baz` hence `this.baz` is `undefined`. Learn more about how `this` works here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this, [How does the “this” keyword work?](https://stackoverflow.com/q/3127429/218196). Besides, it would never ever return `1` because [`typeof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) returns the *type* of a value. `1` is not a type. – Felix Kling Jun 22 '17 at 07:19
  • "should return 1", no. It 'should' return `"number"`, if `this` is `foo`: `return typeof arguments[0].apply(foo);` – Arg0n Jun 22 '17 at 07:22
  • See also [How to access the correct `this` context inside a callback?](https://stackoverflow.com/q/20279484/218196) – Felix Kling Jun 22 '17 at 07:24

2 Answers2

5

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.

xReeQz
  • 311
  • 1
  • 7
1

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

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072