使用此关键字作为class / upper函数的主要function

我一直想弄清楚如何使用我在JavaScript类中声明的variables。 但由于我在里面使用了一个函数,所以现在使用这个关键字,所以我问的是如何使用在一个新的函数中的整个类中声明的variables。

例:

function SomeClass(){ this.classVariable = 1; this.classVariable2 = 2; } SomeClass.prototype.someMethod = function() { return function(){ // do stuff with class variables in here return this.classVariable + this.classVariable2; } } 

我知道你可以完成返回this.classVariable + this.classVariable2但是,这是我的问题的一个例子。

那么如何从另一个函数中检索类variables呢?

一个常见的解决scheme是像这样定义一个variables:

 SomeClass.prototype.someMethod = function() { var that = this; return function(){ // do stuff with class variables in here return that.classVariable + that.classVariable2; } } 

另一个解决scheme是使用绑定 :

 SomeClass.prototype.someMethod = function() { var fun = function() { // do stuff with class variables in here return this.classVariable + this.classVariable2; } return fun.bind(this); } 

bind返回的函数bindthis函数,使函数不会丢失它的上下文:

 SomeClass.prototype.someMethod = function() { return function(){ // do stuff with class variables in here return this.classVariable + this.classVariable2; }.bind(this); } 

你可以使用那个=这个成语。 在成员函数中定义一个variables(通常命名为“that”,但无关紧要),闭包将能够通过该引用访问对象。