Snewedon
Snewedon

Reputation: 2460

Javascript passing variables to timeout function

I'm trying to set a value after a amount of time.

For some reason I can't access the variable when in the function

setTimeout(function() {
    console.log('hello');
    this.list[this.listIndex].glamour.show = true;           
}, 1000);

I'm inside a VueJS method and I'm trying to access properties of a VueJS template.

Upvotes: 0

Views: 138

Answers (2)

donnie
donnie

Reputation: 66

this refers to the object from which you call the function. By default it's set to the window object.

function sayHello () {
    alert("Hello, I'm " + this.nickname + ".");
}
function make (nickname) {
    return {
        nickname: nickname,
        sayHello: sayHello
    };
}
bob = make("Bob");
jim = make("Jim");
nickname = "Window";
bob.sayHello(); /////////////// alerts "Hello, I'm Bob."
jim.sayHello(); /////////////// alerts "Hello, I'm Jim."
sayHello(); /////////////////// alerts "Hello, I'm Window."
window.sayHello(); //////////// alerts "Hello, I'm Window."
setTimeout(sayHello, 0); ////// alerts "Hello, I'm Window."
setTimeout(bob.sayHello, 0); // alerts "Hello, I'm Window."

To get around this behaviour you have at least 2 possibilities:

// a closure
setTimeout(function () { bob.sayHello(); }, 0);
// the .bind() method
setTimeout(sayHello.bind(bob), 0);

Upvotes: 0

vegazz
vegazz

Reputation: 1441

You need to create a variable that refers to the current object:

var self = this;
setTimeout(function() {
  console.log('hello');
  self.list[self.listIndex].glamour.show = true;
}, 1000);

Upvotes: 3

Related Questions