Javascript 如何使用setTimeout设置此上下文的

Javascript 如何使用setTimeout设置此上下文的,javascript,jquery,bind,underscore.js,Javascript,Jquery,Bind,Underscore.js,我需要在特定上下文中执行以下函数 setTimeout(function () { myFunction(); }, 1000 * 60); var changeDateFormat = function () { console.log(this); // this should be $('.myClass') // but I need to set it from setTimeout

我需要在特定上下文中执行以下函数

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
};
附言:
我使用的是下划线.js和jQuery。

您可以使用

下面是一个例子:

正如James所说,您也可以像jQuery内部一样使用
apply

proxy = function() {
    return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
第一个
apply
参数是执行上下文(使用
this
可以访问的内容),第二个参数是要传递给myFunction的其他参数。
调用
函数是相同的,但接受附加参数的方式略有不同


或在下划线.js中使用

setTimeout(_.bind(myFunction, $(".myClass")), 100);

您可以使用JavaScript调用或应用函数设置函数的作用域。关于它们如何工作的详细信息,请参见此


通过设置范围,您可以将“this”设置为您想要的任何内容。

这样的设置可能会有所帮助:

var changeDateFormat = function () {
    console.log(this); // this should be $('.myClass') 
                       // but I need to set it from setTimeout
                       // any hints
};

function callWithContext() {
   changeDateFormat.call($(".class"));
}

setTimeout(callWithContext, 1000 * 60);
调用要调用的函数,将所需的
对象作为第一个参数传递:

setTimeout(function () {
    myFunction.call($('.myClass'));
}, 1000 * 60);
您可以使用将回调绑定到所需的上下文
这样做的缺点是某些浏览器可能不支持这种功能。但遵循JS的基本原则,闭包也会为您提供完美的服务:

var callBack = (function(that)
{//<-- use "that" instead of "this"
    return function()
    {
        console.log(that);
    };
}($('.myClass')));//<-- pass value for that here
setTimeout(callBack,60000);
var callBack=(函数(that)
{//
var callBack = (function(that)
{//<-- use "that" instead of "this"
    return function()
    {
        console.log(that);
    };
}($('.myClass')));//<-- pass value for that here
setTimeout(callBack,60000);