如何在包含函数的方法中使用类变量
How to use class variables inside methods that contain functions?
假设我有这段代码:
MyClass = {
classVar1: 'Teddy Bear',
classVar2: 'Boogy Man',
firstMethod: function() {
console.log('I love my' + this.classVar1); // works
setTimeout(function() {
console.log('But I hate the ' + this.classVar2); // does not work
}, 2000);
someElement.addEventListener('click', function() {
console.log('I also hate the ' + this.classVar2); // also does not work
});
}
};
MyClass.firstMethod();
因为firstMethod
里面有一个嵌套函数,所以我无法访问第二个类变量。我该如何解决这个问题?
您可以使用
bind
强制this
值正确:
setTimeout((function() {
console.log('But I hate the ' + this.classVar2);
}).bind(this), 2000);
或者,您可以只捕获变量中的原始this
值:
var that = this;
setTimeout(function() {
console.log('But I hate the ' + that.classVar2);
}, 2000);
你在这里创建的是一个javascript对象,而不是一个类。为了创建一个类,你需要做这样的事情:
var MyClass = function() {
var self = this; // Create a local variable that stores a pointer to 'this'
this.classVar1 = 'Teddy Bear';
this.classVar2 = 'Boogy Man';
this.firstMethod = function() {
console.log('I love my' + self.classVar1); // use self instead of this
setTimeout(function() {
console.log('But I hate the ' + self.classVar2); // use self instead of this
}, 2000);
someElement.addEventListener('click', function() {
console.log('I also hate the ' + self.classVar2); // use self instead of this
});
}
};
然后使用上面的类创建一个这样的对象:
var myObject = new MyClass();
myObject.firstMethod();
希望这有帮助。
您可以存储对父this
的引用;
firstMethod: function() {
var _this = this;
console.log('I love my' + this.classVar1);
setTimeout(function() {
console.log('But I hate the ' + _this.classVar2);
}, 2000);
someElement.addEventListener('click', function() {
console.log('I also hate the ' + _this.classVar2);
});
}
要在您自己的类中引用您的变量,您只需
Class={
classvar:'x'
function myfunction(){
return this.classvar;
}
}
Class.myfunction(); // should return x
this.variable 应该足以访问类或对象中方法中的全局变量
相关文章:
- 引用类变量中的原型方法
- 如何在类内部调用类的方法
- 如何在ajax回调中使用类变量
- 可以“;超级“;可以在子类的方法内部使用,在不直接引用的情况下调用相应的超类方法
- Javascript ES6共享类变量
- 从类函数中删除类变量
- 引导程序是否有显示隐藏类的方法
- 如何在Typescript中的回调中访问类变量
- 为什么 Javascript 中的类变量在尝试多次调用它们或将它们分配给局部变量时会消失
- 是受(GWT)基类中方法数量影响的JavaScript对象的大小
- jQuery/can'我找不到避免代码添加类的方法
- 使用类/构造函数与变量方法时的作用域不同
- Javascript 从父级中定义的继承类方法访问类变量
- 如何在包含函数的方法中使用类变量
- 如何调用父类'方法从JavaScript中的子类中删除,以便parent's的局部变量将是可访问的
- 如何使变量在类的方法中可用
- 在父类的方法中使用子类的类变量,这样变量就可以动态地改变(javascript)
- Java-script,谷歌chrome扩展:未定义的类变量,在方法中引用的回调
- ES6:使用_this_从方法中访问类变量
- 在js中,在另一个类的主体中使用类的方法(具有this.variable形式的变量)