jQuery – How to Invoke an Object’s Fields Within a Function Closure

Home / Blog / jQuery – How to Invoke an Object’s Fields Within a Function Closure

This may be common knowledge for many, but since I go back and forth between jQuery and Prototype, I find myself always researching how each Javascript frameworks handle context switching. A frequent problem I run into is having a custom Javascript object who has a function that contains a function closure that tries to call the object itself (that’s a lot to take in). Lets look at an example …

Suppose we have the following jQuery Javascript class:


var SomeObj= function() {
	this.init();
}
$.extend(SomeObj.prototype, {
        init: function(){
             $('button').click(function(index){
                  // I'd like to call this.someMethod();
             });
        },
        someMethod: function(){
            alert('Hello World!');
        }
});

In the code above, I can’t just call ‘this.someMethod()’ within the function closure due to the context at which it will be executed. At the time the code is run, buy yasmin price ‘this’ will be set to the button who fires the event. If we want to call a method or field on the custom javascript object, we have to cache its instance within a local variable. If we modify the code as below, it will now work:


var SomeObj= function() {
	this.init();
}
$.extend(SomeObj.prototype, {
        init: function(){
             var self = this;
             $('button').click(function(index){
                  self.someMethod();
             });
        },
        someMethod: function(){
            alert('Hello World!');
        }
});

Now, lets not get all bothered over semantics. I know that the above example is not a real-world example of anything useful; however, the approach I’ve taken may prove helpful for someone in a different scenario.

Leave a Comment