简体   繁体   中英

How to use class variables inside methods that contain functions?

So lets say I have this code:

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();

Because there is a nested function inside of firstMethod I cannot access the second class variable. How do I solve this?

You can use bind to force the this value to be correct:

setTimeout((function() {
    console.log('But I hate the ' + this.classVar2);
}).bind(this), 2000);

Alternatively, you can just capture the original this value in a variable:

var that = this;
setTimeout(function() {
    console.log('But I hate the ' + that.classVar2);
}, 2000);

You can store reference to parent 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);
    });
}

What you've created here is a javascript object and not a class. In order to create a class you would need to do something like this:

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
        });
    }
};

And then use the above class to create an object like this:

var myObject = new MyClass();
myObject.firstMethod();

Hope this helps.

To refer to your variable within your own class you simply have to

Class={
     classvar:'x'
     function myfunction(){
           return this.classvar;
     }
 }
 Class.myfunction(); // should return x

should be enough this.variable to access a global variable in a method within a class or an object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM