2

Here is my code:

var timer = 
{
    i: "Hello",

    start: function()
    {       
        var self = this;             
        window.setInterval(self.tick, 1000);     
    },

    tick: function()
    {
        console.log(this.i);
    }       
}

timer.start();

Why the javascript console displays undefined?

1

3 Answers 3

3

Your passing a reference to tick, but not the scope. try:

start: function(){       
    var self = this;             
    window.setInterval(function(){self.tick();}, 1000);     
}

Or use bind (look at the browser compatibility first)

Sign up to request clarification or add additional context in comments.

Comments

2

change this.i to timer.i

Or use an object declaration like

function timer() {
var self = this;
.. etc.

Comments

1

suggest change window.setInterval(self.tick, 1000); to

window.setInterval(self.tick.bind(self), 1000);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.