JavaScript中method内部的method关键字的逻辑是什么?

5

可以有人告诉我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;}
     }

阅读此链接:http://javascript.crockford.com/private.html - hereandnow78
在这两种情况下,它都是指 B 实例,因此您可以在其上调用 a/x - pimvdb
1
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this - Felix Kling
this 是在运行时而不是解析/定义时确定的。仅仅通过查看定义,你无法知道 this 将引用什么。这完全取决于函数被调用的方式。 - Felix Kling
1个回答

3
如果你调用一个方法:
a.b.c.d();

那么在方法内部,this 指向的是除最后一个函数名以外的所有内容,包括 a.b.c

如果您调用构造函数:

var x = new Something();

那么在Something()内部,this是一个新的对象。

在其他地方,this是全局对象(在浏览器中等同于window)。

this永远不是原型。它可以有一个原型。

在你的例子中:

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

thisA(不一定是A.B的原型),如果该方法被调用为A.B(),则代表A;如果该方法被调用为new A.B(),则代表一个新对象。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接