Skip to content Skip to sidebar Skip to footer

How Can I Maintain Control Of The This Keyword When Extending Prototypes In JQuery?

I'm implementing a class-like structure in jQuery, but I'm having some trouble when I try to call some of my functions. This is how the structure is setup: MyClass = function(name)

Solution 1:

You need to assign this to another variable, because of how scope works.

MyClass = function(name) {
    this.init(name);
}
$.extend(MyClass.prototype, {
    init: function(theName) {
        this.myFunction(); // works
        var that = this;
        $('.myclass').each(function(){
                this.myFunction(); // doesn't work
                that.myFunction(); // should work
        });
    },
    myFunction = function(){}
});

Solution 2:

The .each() function changes the context of this (as does any function in JavaScript).

You need to do something like this:

MyClass = function(name) {
    this.init(name);
}
$.extend(MyClass.prototype, {
    init: function(theName) {
        this.myFunction(); // works
        var myClass = this;
        $('.myclass').each(function(){
                myClass.myFunction(); // doesn't work
        });
    },
    myFunction = function(){}
});

Solution 3:

MyClass = function(name) {
    this.init(name);
}
$.extend(MyClass.prototype, {
    init: function(theName) {
        this.myFunction(); // works
        temp = this;
        $('.myclass').each(function(){
                temp.myFunction(); // works
        });
    },
    myFunction = function(){}
});

Try that. :)


Post a Comment for "How Can I Maintain Control Of The This Keyword When Extending Prototypes In JQuery?"