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);

2 Answers 2

2

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(){
    });
};
Sign up to request clarification or add additional context in comments.

Comments

1

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(){
    });
};

Comments

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.