如何从内部重新加载jquery插件

How to reload jquery plugin from inside?

本文关键字:加载 jquery 插件 新加载 内部      更新时间:2023-09-26

我需要从内部重新加载我的函数,我做了一个小片段:

function jqueryPlugin (selector, properties) {
    this.properties = {
        foo: properties.foo || 'foo',
        bar: properties.bar || 'bar'
    };
    // this.element = $(selector);
    // ...
    console.log('element loaded... plugin start working...')
    // ...
    this.reload = function (properties) {
        // ...
        this(selector, properties); // ??
    };
};
var instance = new jqueryPlugin('.foobar', {foo:'foooo'});
// ...
instance.reload({foo:'foobar'});

如您所见,它说this不是一个函数。但是this怎么能不是一个功能呢?我错过了什么?

这是因为this是一个对象,而不是一个函数。尝试改用init函数,如@RoryMcCrossan建议的那样:

function jqueryPlugin (selector, properties) {
    this.init = function(selector, properties){
        this.properties = {
            foo: properties.foo || 'foo',
            bar: properties.bar || 'bar'
        };
        
        //test if `this` is a function: console.log(this);
        // this.element = $(selector);
        // ...
        console.log('element loaded... plugin start working...')
        // ...
    };
    this.reload = function (properties) {
        // ...
        this.init(selector, properties); // ??
    };
    this.init(selector, properties);
};
var instance = new jqueryPlugin('.foobar', {foo:'foooo'});
// ...
instance.reload({foo:'foobar'});