這看起來很複雜,但其實很簡單。這個函數做的是返回一個函數,你傳遞的參數綁定到thisValue
。
下面是一個例子:
var bind = function(func, thisValue) {
return function() {
return func.apply(thisValue, arguments);
}
}
var x = {
"key": "the value"
};
var y = {
"key": "the y value"
};
function alert_key() {
alert(this.key);
}
var bound_function = bind(alert_key, x);
bound_function(); // alerts "the value"
var bound_function2 = bind(alert_key, y);
bound_function2(); // alerts "the y value"
認識到,在this.key
this
勢必x
,因爲它是在func.apply(thisValue, arguments)
arguments
的第一個參數是很重要的是一個神奇的JavaScript變量將包含所有傳遞給函數的參數。所以func.apply(thisValue, arguments)
真的只是通過所有參數,但將this
上下文設置爲thisValue
(或在我的示例中爲x
和y
)。
舉例額外的參數(S):
var bind = function(func, thisValue) {
return function() {
return func.apply(thisValue, arguments);
}
}
var x = {
"key": "the value"
};
function alert_key(another_value) {
alert(this.key + " " + another_value);
}
var bound_function = bind(alert_key, x);
bound_function("another value"); // alerts "the value another value"
bound_function("value y"); // alerts "the value value y"
謝謝你在這個Frits去!這並不完全是我堅持的,雖然:-)。見下文。 – aaronfalloon
啊我看到了,我讀了'閉包'並跳過了其餘的問題。傻我。 – Halcyon