Unknown
Unknown

Reputation: 257

how can I access this inside a function without using that or self in javascript?

Im trying to write some OOP in javascript, and I stumbled upon a problem that I am sure Im going to have later on in my code and wish to deal with it now.

for example take this code:

var FeedClass = function(){

    this.init = function(){
        this.loadItems();
    },
    this.loadItems = function(){
        var that = this; // heres my problem
        function inner(){
            that.startLoading();
        }
        inner();
    },
    this.startLoading = function(){
        alert("started Loading");
    }

    this.init();
};

var feed = new FeedClass();

the problem is Im going to use a lot of inner functions that will call "this", my code will be messy if I kept writing var that = this inside every scope. Is there another pattern I can use or a way to get around it?

Upvotes: 1

Views: 38

Answers (1)

Guffa
Guffa

Reputation: 700252

You can use the call method to set the context for the function:

this.loadItems = function(){
    function inner(){
        this.startLoading();
    }
    inner.call(this);
},

The apply method works similarly, the difference is how you specify parameters in the call.

You can also use the bind method to set the context of a function. That allows you to bind the context to the function and pass the function reference on to be called later:

this.loadItems = function(){
    function inner(){
        this.startLoading();
    }
    var i = inner.bind(this);
    i();
},

Note: The bind method is not supported in IE 8 or earlier.

Upvotes: 2

Related Questions