Denis Priebe
Denis Priebe

Reputation: 2855

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?

Upvotes: 0

Views: 61

Answers (4)

Oleksandr T.
Oleksandr T.

Reputation: 77482

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

Upvotes: 1

Digitrance
Digitrance

Reputation: 759

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.

Upvotes: 1

zardilior
zardilior

Reputation: 2978

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

Upvotes: 0

Alexis King
Alexis King

Reputation: 43852

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

Upvotes: 4

Related Questions