gpt4 book ai didi

javascript - js inside method in method 中this关键字的逻辑是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:19:32 25 4
gpt4 key购买 nike

谁能告诉 js 中的“this”关键字..我看了例子。有一点我不能理解。

   A.B=function()
{
this.x(5); // this refers to prototype of A.B
}


A.B.prototype= {
x:function(p)
{ this.a(p); // this refers to prototype of A.B again
// but I expect that this refers to protoype of x ???

},
a:function(p){ return p;}
}

最佳答案

如果你调用一个方法:

a.b.c.d();

然后 this 是方法内部的 a.b.c(除最终函数名称之外的所有内容)。

如果调用构造函数:

var x = new Something();

然后 this 是 Something() 中的一个新对象。

在其他任何地方 this 都是全局对象(与浏览器中的 window 相同)。

this 绝不是原型(prototype)。这可以一个原型(prototype)。

在你的例子中:

A.B = function() {
this.x(5);
}

thisA(不必是 A.B 的原型(prototype))如果该方法被称为 A.B () - 如果该方法被称为 new A.B(),则它是一个新对象。

关于javascript - js inside method in method 中this关键字的逻辑是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14648365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com