1

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?

2
  • 2
    You should perhaps check the Function.bind() method in javascript. It might answer your question Commented Jun 22, 2014 at 22:18
  • @Jhecht thanks, could you possibly give me an example of using `bind()' with the code above, so i can see how it works. Commented Jun 22, 2014 at 22:20

1 Answer 1

2

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.

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

2 Comments

perfect, exactly what i wanted to hear.
This also does the same (effectively) the same thing as .bind If you'd like I could make an answer to show you some of the differences.

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.