1

This is the code snippet that makes me confusing:

var timer = 
{
    start: function()
    {
        var self = this;

        /*Why the code below doesn't write to this:
            window.setInterval(self.tick, 1000).*/

        //Instead, it embedded into a function like this:
        window.setInterval(function(){self.tick();}, 1000)
    },
    tick: function()
    {
        console.log("tick!");
    }       
}

timer.start();
0

3 Answers 3

2

The reason is that JavaScript's this is dynamic. When you call a function like:

object.func();

this will be set to object. However, when you call a function plainly:

func();

Or pass it to a number of other functions (setInterval included), this will be set to the global object (window, usually).

Thus, when you just pass self.tick to setInterval, then this inside of tick will be the global object, not timer. When you pass function() { self.tick(); }, it is self (timer).

Here, it makes no difference, since tick does not access this, but if tick accessed this, you'd probably want to use function() { self.tick(); }, because otherwise, you'll be modifying properties of the global object, not timer.

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

Comments

1

function(){self.tick();} is easier to expand later than self.tick. It's kind of like the difference between using curly braces (or not) around an if block that contains only one statement.

2 Comments

And why wouldn't someone later just add whatever to tick instead?
Because maybe tick could be used elsewhere.
0

Another reason we use: window.setInterval(function(){self.tick();}, 1000) is to conform to "Single responsibility" design principle. tick() should do only 1 job: tick. If you need to do more jobs when the timer fires, you should write another function and get it called inside the event handler instead of modifying the tick(). For example:

window.setInterval(function(){
    self.tick();
    self.notify();
    .....
    }, 1000)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.