下面是我正在尝试做的一个伪例
在非严格模式下,这是有效的,但在严格模式下,当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);发布于 2013-04-21 01:36:43
当一个字符串被setInterval解释时,它在全局作用域中,而不是在调用它的函数的作用域中。传递要调用的实际函数,而不是字符串:
setInterval(bar.Save, 10000);如果您允许修改bar或bar.Save,并且希望自动获取更改,则应该传递一个每次都会对其重新求值的函数:
setInterval(function() { bar.Save(); }, 10000);https://stackoverflow.com/questions/16123130
复制相似问题