如何在包含函数的方法中使用类变量

How to use class variables inside methods that contain functions?

本文关键字:类变量 方法 包含 函数      更新时间:2023-09-26

假设我有这段代码:

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 应该足以访问类或对象中方法中的全局变量