开发者

Call an external function from inside function in jQuery

开发者 https://www.devze.com 2023-01-14 04:01 出处:网络
I try to extend jQuery, but when I call myTest this will return this.myTest.test() is undefined... can someone tell me why...

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(){
      开发者_StackOverflow  alert('test'); 
    };

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

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消