tags:

views:

48

answers:

2

I try to extend jQuery, but when I call myTest this will return this.myTest.test() is undefined...

can someone tell me why...

(function($) {
    $.fn.myTest=function() {

        var x=function() {
            this.myTest.test();

            var b = function() {
                this.myTest.coba();
            }
        }

        x();

        return this.each(function(){
        });
    };

    $.fn.myTest.test = function(){
        alert('test'); 
    };

    $.fn.myTest.coba = function(){
        alert('coba'); 
    };

    $.fn.myTest.iseng = function(){
        alert('iseng'); 
    };
})(jQuery);
+1  A: 

The this inside the x() function is not the jQuery object, but is the window, as far as I know. Here's what you need...

$.fn.myTest = function() {
    var that = this;
    var x=function() {
        that.myTest.test();

        var b = function() {
            that.myTest.coba();
        }
    }

    x();

    return this.each(function(){
    });
};
Shrikant Sharat
thank's ... i get'it now..
comenk
+1  A: 

You call this.myTest.test(); from within the nested function x. Thus this won't point to the $.fn.myTest object.

You will run into the same problem with this.myTest.coba(); in function b.

To solve that you have to store the context of the $.fn.myTest object beforehand to access it:

$.fn.myTest=function() {

    var self = this;
    var x=function() {
        self.myTest.test();

        var b = function() {
            self.myTest.coba();
        }
    }

    x();

    return this.each(function(){
    });
};
jfs
thank's a lot... this work..
comenk