2013-02-01 39 views
4

任何人都可以在js中告诉“this”这个关键字。我看了一些例子。有一点我不明白。这个关键字在js里面方法里的方法是什么逻辑?

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;} 
    } 
+0

阅读此:http://javascript.crockford.com/private.html – hereandnow78

+0

在这两种情况下,它指的是'B'实例,所以你可以调用'a' /'x'。 – pimvdb

+1

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/这个 –

回答

2

如果你调用一个方法:

a.b.c.d(); 

然后thisa.b.c方法(一切,除了最后的函数名称)的内部。

如果调用构造函数:

var x = new Something(); 

然后this是东西里面一个新的新鲜对象()。

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

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

在您的例子:

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

thisA(这并不一定是A.B原型),如果该方法被称为A.B() - 并且是一个新的对象,如果该方法被称为new A.B()