jQuery plugin public method/function

最后都变了- 提交于 2019-12-09 03:19:05

问题


I am trying to achieve something like the following but dont know whats wrong:

$.a = function() {

// some logic here

function abc(id) {
   alert('test'+id);
}


}

$.a.abc('1');

I tried using the return function, but that doesnt seem to work either. Can someone please help.

Thank you for your time.


回答1:


Since $.a must be a function in itself, you'll have to add the abc function as a property to the $.a function:

$.a = function () {
    // some logic here...
};

$.a.abc = function (id) {
    alert('test' + id);
};

If abc must be defined from within the $.a function, you can do the following. Do note that $.a.abc will not be available until $.a has been called when using this method! Nothing inside a function is evaluated until a function is called.

$.a = function () {

    // Do some logic here...

    // Add abc as a property to the currently calling function ($.a)
    arguments.callee.abc = function (id) {
        alert('test' + id);
    };
};

$.a();
$.a.abc('1');



回答2:


$.a = (function(){
    var a = function() {
        //...
    };
    a.abc = function() {
        //...
    }
    return a;
})();


来源:https://stackoverflow.com/questions/1204822/jquery-plugin-public-method-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!