我一直试图弄清楚如何使用我在JavaScript类中声明的变量。但是因为我在其中使用了一个函数,所以this关键字现在使用它,所以我要问的是如何在新函数中使用整个类中声明的变量。
示例:
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但是,这是我的问题的一个例子。
那么如何从另一个函数中检索类变量呢?
答案 0 :(得分:2)
一个常见的解决方案是定义一个that
变量,如下所示:
SomeClass.prototype.someMethod = function() {
var that = this;
return function(){
// do stuff with class variables in here
return that.classVariable + that.classVariable2;
}
}
另一种解决方案是使用bind:
SomeClass.prototype.someMethod = function() {
var fun = function() {
// do stuff with class variables in here
return this.classVariable + this.classVariable2;
}
return fun.bind(this);
}
答案 1 :(得分:2)
bind
将返回的函数发送到this
,以便函数不会丢失其上下文:
SomeClass.prototype.someMethod = function() {
return function(){
// do stuff with class variables in here
return this.classVariable + this.classVariable2;
}.bind(this);
}
答案 2 :(得分:1)
你可以使用那个=这个成语。在成员函数中定义一个变量(通常命名为“that”,但无关紧要),该变量指向this
,闭包将能够通过该引用访问该对象。