Javascript 将此关键字用于类/上级函数的主函数
我一直在试图找出一个解决方案,如何使用我在JavaScript类中声明的变量。但是因为我在里面使用了一个函数,this关键字现在使用了它,所以我要问的是如何在一个新函数里面使用在整个类中声明的变量 例如:Javascript 将此关键字用于类/上级函数的主函数,javascript,node.js,Javascript,Node.js,我一直在试图找出一个解决方案,如何使用我在JavaScript类中声明的变量。但是因为我在里面使用了一个函数,this关键字现在使用了它,所以我要问的是如何在一个新函数里面使用在整个类中声明的变量 例如: function SomeClass(){ this.classVariable = 1; this.classVariable2 = 2; } SomeClass.prototype.someMethod = function() { return function
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,但这是我问题的一个示例
那么,如何从另一个函数中检索类变量呢?一个常见的解决方案是定义一个这样的变量:
SomeClass.prototype.someMethod = function() {
var that = this;
return function(){
// do stuff with class variables in here
return that.classVariable + that.classVariable2;
}
}
另一个解决办法是使用:
一种常见的解决方案是定义一个变量,如下所示:
SomeClass.prototype.someMethod = function() {
var that = this;
return function(){
// do stuff with class variables in here
return that.classVariable + that.classVariable2;
}
}
另一个解决办法是使用:
将返回的函数绑定到此函数,以便该函数不会丢失其上下文:
SomeClass.prototype.someMethod = function() {
return function(){
// do stuff with class variables in here
return this.classVariable + this.classVariable2;
}.bind(this);
}
将返回的函数绑定到此函数,以便该函数不会丢失其上下文:
SomeClass.prototype.someMethod = function() {
return function(){
// do stuff with class variables in here
return this.classVariable + this.classVariable2;
}.bind(this);
}
你可以用that=这个成语。定义一个经常命名为that的变量,但在成员函数中指向该变量并不重要,闭包将能够通过该引用访问对象。您可以使用that=this习惯用法。定义一个经常命名为该变量的变量,但在指向该变量的成员函数中并不重要,闭包将能够通过该引用访问该对象