-3

Why the value of outcome is 'undefined' in the following example? Kindly explain someone how is this calculated?

<script>
var foo = {
  bar: function() { return this.baz; },
  baz: 1
};

var a = (function(){
  return typeof arguments[0]();
})(foo.bar);

console.log(a);
</script>

Note: I've been through following link and it doesn't explain this example. There is no constructor function here ... How to access the correct `this` inside a callback?

Deadpool
  • 6,416
  • 5
  • 32
  • 64
  • 1
    Don't post the same question [over again](https://stackoverflow.com/questions/54879056/why-output-of-following-example-is-undefined-and-how-is-it-calculated) - this is indeed a dupe of that canonical. `arguments[0]()` invokes whatever function's within `arguments[0]` without a calling context. Like I said in the comment on that question, to retain the calling context, either pass `() => foo.bar()` or use `.bind` – CertainPerformance Feb 26 '19 at 05:53
  • @CertainPerformance [How does the “this” keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) would be a better dupe target, imho... – Andreas Feb 26 '19 at 05:54
  • 1
    `this` in `bar` refers `arguments` object of `a` when you call `bar` like `arguments[0]()` from `a`. Notice, that `arguments` is an object, not an array. See [a fiddle](https://jsfiddle.net/hbuaty19/). – Teemu Feb 26 '19 at 06:10
  • 1
    Use this code `return typeof ( arguments[0].call(foo) );` – Ehsan Feb 26 '19 at 06:15

1 Answers1

1

arguments[0]() is executing in the Window context, but it does not have any object property defined in the name bar (which is a property of foo). This is why you get undefined. To solve the issue, you can bind the object.

Change

foo.bar

To

foo.bar.bind(foo)

var foo = {
  bar: function() { return this.baz; },
  baz: 1
};
var a = (function(){
  console.log(this.constructor.name); // Window
  return typeof arguments[0]();
})(foo.bar.bind(foo));

console.log(a);
Mamun
  • 58,653
  • 9
  • 33
  • 46
  • _"Kindly **explain** why in following..."_ – Andreas Feb 26 '19 at 05:51
  • can you please tell what does arguments[0] here is referring to? either -- foo.bar or returned value '1'? or whatever? – Deadpool Feb 26 '19 at 05:52
  • @Deadpool, `arguments[0]` refers to the function which you are passing to the function. – Mamun Feb 26 '19 at 05:56
  • @Mamun - it refers to the function or the argument that we are passing in the function??? (like if we passed name, age as arguments in foo.bar???) – Deadpool Feb 26 '19 at 05:57
  • @Deadpool, it will refer what you pass to the function as parameter. – Mamun Feb 26 '19 at 05:59
  • "_`arguments[0]()` is executing in the Window context_" No, it isn't. It is executed in the context of `arguments` object of `a`, because the passed function reference becomes a property of the arguments object. – Teemu Feb 26 '19 at 07:01