1

I am new to javascript, why this code return undefined?

    const foo = {  
      bar: function() { return this.baz; },
      baz: 1,
    };

    console.log((function() {
      return typeof arguments[0]();
    })(foo.bar));
Inovramadani
  • 1,955
  • 3
  • 14
  • 34
  • Where did you find this code? That IIFE and `arguments[0]` thing looks unnecessarily complicated and irrelevant to your question. – Bergi Jun 15 '17 at 04:27
  • When you are executing arguments[0]() `this` refers to the context it was called in, in this case, it would most likely be `window` and `window` won't have a property called `baz` – JohanP Jun 15 '17 at 04:29
  • @Tushar Are there? Feel free to reopen and answer, but I think the only/main problem is the misunderstanding of the [`this` keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) – Bergi Jun 15 '17 at 04:30
  • @JohanP Actually `this` will refer to the `arguments` of the IIFE, but yes it's just weird. – Bergi Jun 15 '17 at 04:30

1 Answers1

-1

If you are expecting an answer of number that can not be returned from you code. This is a misunderstanding of this keyword (as pointed out by @Tushar @Bergi)

The following code does it.

function Foo(){
    this.baz = 1;
};

Foo.prototype.bar = function() {
    "use strict";
    return this.baz;
}

var foo = new Foo();
console.log((function() {
    "use strict";
    return typeof arguments[0];
})(foo.bar()));
Prakash N
  • 1,020
  • 1
  • 8
  • 20