【问题标题】:what is the logic of this keyword in js inside method in method?js inside method in method中this关键字的逻辑是什么?
【发布时间】:2013-02-01 14:22:19
【问题描述】:

谁能告诉 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;}
     }

【问题讨论】:

标签: javascript web function-prototypes


【解决方案1】:

如果你调用一个方法:

a.b.c.d();

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

如果调用构造函数:

var x = new Something();

那么this 是Something() 中的一个新对象。

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

this 从来都不是原型。这可以一个原型。

在你的例子中:

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

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

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 1970-01-01
    • 2022-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    相关资源
    最近更新 更多