下面是我想做的一个伪例子
在非严格模式下,这是有效的,但在严格模式下,当setInterval触发时,我得到一个未定义的错误。这个脚本由另一个jquery脚本作为插件调用,然后调用init部分。
从这里阅读它似乎是一个全局作用域/上下文问题,但我不知道如何进行
(function($, window, document) {
'use strict'; // remove and things work
var opts,test;
test = function(options) {
opts = $.extend(test.prototype.opts, test.prototype.defaults, options);
};
test.prototype.Save = function () {
console.log('hi');
};
test.prototype.defaults = {
_interval_id: null
};
test.prototype.opts = {};
$.bla.plugins.foobar = function() {
var base = this,
bar;
base.init = function() {
bar = new test();
opts = test.prototype.opts;
bar.Save(); // works
opts._interval_id = setInterval('bar.Save();', 10000); // called but bar is not defined
};
};
})(jQuery, window, document);
当一个字符串被setInterval
解释时,它在全局作用域中,而不是调用它的函数的作用域中。传递要调用的实际函数,而不是字符串:
setInterval(bar.Save, 10000);
如果您允许修改bar
或bar.Save
,并且您希望自动拾取更改,您应该传递一个函数,每次重新计算它:
setInterval(function() { bar.Save(); }, 10000);