Javascript - Why call method is not working correctly? - Stack Overflow

Please refer - var o = {x: 6};function a() {this.x = 3;this.y = function() {alert(this.x)}}var a1 =

Please refer - /

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?

Please refer - https://jsfiddle/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?

Share Improve this question edited Jul 8, 2015 at 14:04 jcubic 66.8k58 gold badges249 silver badges455 bronze badges asked Jul 8, 2015 at 14:03 anand patilanand patil 5072 gold badges9 silver badges27 bronze badges 2
  • Change a1.y.call() => a1.y.call(a1); – elad.chen Commented Jul 8, 2015 at 14:05
  • 3 Why would you do this? – Evan Davis Commented Jul 8, 2015 at 14:05
Add a ment  | 

2 Answers 2

Reset to default 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.

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744904636a4600179.html

相关推荐

  • Javascript - Why call method is not working correctly? - Stack Overflow

    Please refer - var o = {x: 6};function a() {this.x = 3;this.y = function() {alert(this.x)}}var a1 =

    1天前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信