我需要在特定上下文中执行以下函数。
setTimeout(function () {
myFunction();
}, 1000 * 60);
var changeDateFormat = function () {
console.log(this); // this should be $('.myClass')
// but I need to set it from setTimeout
// any hints
};
附注:
我正在使用 Underscore.js 和 jQuery。
最佳答案
您可以使用jQuery.proxy .
setTimeout($.proxy(myFunction, $(".myClass")), 1000 * 60);
这是一个示例:http://jsfiddle.net/UwUQD/1/
正如 James 所说,您也可以像 jQuery 内部那样使用 apply
:
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
第一个 apply
参数是执行上下文(您可以使用 this
访问),第二个参数是您想要传递给 myFunction 的其他参数。 call
函数是相同的,但接受的附加参数略有不同。
或使用bind在 Underscore.js
setTimeout(_.bind(myFunction, $(".myClass")), 100);
关于javascript - 如何使用 setTimeout 设置 this 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13456834/