2012-11-08 38 views
23

有一些功能,这是做了长时间的工作,并提供回调。如何将上下文传递给匿名函数?

someFunc: function(argument, callback, context) { 
    // do something long 

    // call callback function 
    callback(context); 
} 

在实际应用中我使用这个功能

someFunc('bla-bla', function (context) { 
    // do something with this scope 
    context.anotherFunc(); 
}, this); 

如何实现回调函数没有通过context参数?

需要一些这样的:

someFunc('bla-bla', function() { 
    // do something with this scope 
    this.anotherFunc(); 
}, this); 
+1

因此,在你最后的例子似乎要传递的上下文(的东西至少)你只是好奇如何引用的说法,如果它不叫? –

+0

你正在传递参数,你只是没有使用它。我不明白为什么。 – bfavaretto

+2

@bfavaretto:OP是通过使其进入回调使用它,以便回调可以采取的外'this'值的方法的优点。所以问题是如何实现最后一个代码块......在回调中获得正确的this,所以它不需要作为参数传递。 –

回答

37

接受的答案似乎有些过时。假设您使用的是相对较新的浏览器,则可以在vanilla javascript中使用Function.prototype.bind。或者,如果您使用underscorejQuery,则可以分别使用_.bind$.proxy(如果需要,将回退到call/apply)。

下面是这三个选项的一个简单的例子:

// simple function that takes another function 
// as its parameter and then executes it. 
function execute_param(func) { 
    func(); 
} 

// dummy object. providing an alternative context. 
obj = {}; 
obj.data = 10; 

// no context provided 
// outputs 'Window' 
execute_param(function(){ 
    console.log(this); 
}); 

// context provided by js - Function.prototype.bind 
// src: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind 
// outputs 'Object { data=10 }'' 
execute_param(function(){ 
    console.log(this); 
}.bind(obj)); 

// context provided by underscore - _.bind 
// src: http://underscorejs.org/#bind 
// outputs 'Object { data=10 }' 
execute_param(_.bind(function(){ 
    console.log(this); 
},obj)); 

// context provided by jQuery - $.proxy 
// src: http://api.jquery.com/jQuery.proxy/ 
// outputs 'Object { data=10 }' 
execute_param($.proxy(function(){ 
    console.log(this); 
},obj)); 

你可以找到在这里的jsfiddle代码:http://jsfiddle.net/yMm6t/1/注:确保开发者控制台是打开的,否则你将看不到任何输出

+0

是的。现在,我使用的是强调无处不在:) – acelot

+0

@PiONeeR是啊,我也一样:)你可能要重新考虑什么应该是公认的答案。 – EleventyOne

+8

这应该是被接受的答案。 – Gamak

13

使用Function.prototype.call调用的函数,手动设置功能的this值。

someFunc: function(argument, callback, context) { 
    callback.call(context); // call the callback and manually set the 'this' 
} 

现在您的回调具有预期的this值。

someFunc('bla-bla', function() { 
    // now 'this' is what you'd expect 
    this.anotherFunc(); 
}, this); 

当然你也可以通过像正常参数在.call调用。

callback.call(context, argument); 
相关问题