1

Please refer - https://jsfiddle.net/ta2u2z9a/

var o = {
    x: 6
};

function a() {
    this.x = 3;
    this.y = function() {
        alert(this.x)
    }
}

var a1 = new a();
a1.y.call(); //shouldn't it alert 3?

a1.y.call(o) //is alerting 6, correct!

Why is the first alert, alerting undefined? shouldn't it alert 3?

jcubic
  • 61,973
  • 54
  • 229
  • 402
anand patil
  • 507
  • 1
  • 9
  • 26

2 Answers2

10

The first argument to .call() needs to be the "owner object" of the method:

a1.y.call(a1);

What's going on?

When you call a method "naturally" (e.g. a1.y()), the value of this is automatically set to the object (e.g. a1).

When using the function not as a method (e.g. var x = a1.y; x();), the value of this is either the global/window object, or null (depending on whether you're in "strict mode" or not).

The .call() method (it's a method of the function) is a way to explicitly set the this value, instead of having it automatically assigned. When using .call(), you have to supply the this value yourself, as the first argument.

cloudfeet
  • 12,156
  • 1
  • 56
  • 57
  • If you don't pass object you get undefined as this and you will get window object as this if you don't use strict mode. – jcubic Jul 08 '15 at 14:06
0

Because you have not sent the expected "this" parameter in call() as an argument so this is undefined in that function.

If you are not passing any argument to call() then no need to use it. Simply call the method on the object.

Baraja Swargiary
  • 381
  • 2
  • 10