我正在尝试创建一个 super 简单的插件。这是我的代码:
var methods = {
init: function (userOptions) {
console.log('init');
setInterval(this.update, 1000);
},
update: function(){
console.log(this);
}
};
$.fn.myPlugin = function (methodOrOptions) {
if (methods[methodOrOptions]) {
return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + methodOrOptions + ' does not exist on jQuery.myPlugin');
}
};
这里 init 调用正常,但更新不是每 1 秒调用一次。我在这里缺少什么?
最佳答案
这绑定(bind)到一个 jquery 对象。它没有this.update。可能会:
setInterval(methods.update.bind(this), 1000);
简单的拿全局方法对象的update函数,绑定(bind)jquery对象就可以了。
关于javascript - 我的插件中未调用更新功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44243933/