2012-11-08 63 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); 
相關問題