Muqito
Muqito

Reputation: 1399

I want to use a anonymous function inside an object

I have this code for a newsfeed that I want to use.

I want it to look kind of like this:

function News(){

    //Load new comments every 5 sec
    setTimeout((function(){
        console.log(this); //Returns Object #News
        this.loadNewsFeed();
    }).call(this),5000);

    this.loadNewsFeed = function(){
        // Implementation here
    }
}

The problem here is that it says the Object News doesn't have an method called loadNewsFeed!

I've already got it to work if I put the anonymous function outside the object News.

Like this:

var news = new News();
//Load new comments every 5 sec
(function loopNews(){
    news.loadNewsFeed();
    setTimeout(loopNews,5000);
})();

So how can I do this inside the object News?

Upvotes: 1

Views: 143

Answers (1)

David Rettenbacher
David Rettenbacher

Reputation: 5120

This should work:

function News()
{
    var self = this;

    this.loadNewsFeed = function(){
        // Implementation here
    };

    //Load new comments every 5 sec
    setInterval(function handler() // setInterval for endless calls
    {
        console.log(self); //Returns Object #News
        self.loadNewsFeed();
        return handler;
    }(), 5000);
}

Explanation:
call(this) invokes the handler directly - and returns undefined to setInterval which means that it's executed immediately but no handler is set.
The handler-function executes in global context so this is the window-object. The local variable self "injects" the current (and desired) this - as self.

Edit 2:
Now executes immediately and registers a handler.

Upvotes: 3

Related Questions