开发者

Running a custom function - settings.func is not a function

开发者 https://www.devze.com 2023-03-02 17:21 出处:网络
I have written a jQuery plugin which I want to call a custom function on like so... (function($) { $.fn.testPlugin= function(options) {

I have written a jQuery plugin which I want to call a custom function on like so...

(function($) {

    $.fn.testPlugin= function(options) {

        var settings = {
            func: null
        };

        if (options) {
            $.extend(settings, options);
        }

        settings.func();
    };

})(jQuery);

In this case I want to run the doSomething function.

$(document).ready(function(){       

    $('div').testPlugin({
        func: 'doSomething'
    });

});

function doSomething() {
    alert('hello');
}

I always get the error settings.func is not a function so I am having to 开发者_如何学运维use:

eval(settings.func+"()");

Intead of:

settings.func();

Which is not ideal! Any ideas why I am getting this?


Because you're assigning a string to settings.func, not a function. Strings are never functions, even if they contain the name of a function.

Functions are first-class citizens, however, which means you can use them as you would any other variable, assigning them to variables or passing them as arguments to other functions. Change:

$('div').testPlugin({
    func: 'doSomething'
});

to

$('div').testPlugin({
    func: doSomething
});

and it should work.

0

精彩评论

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

关注公众号