感謝您的回答評論。
命名函數是使用閉包模式時的一個解決方案,例如。 但不適用於有界函數: 函數名稱引用原始函數,而不是有界實例。
一些示例:
function listener(s,ev){
"use strict";
if (ev.target.value == s){
console.log("<bounded> I found " + s+ ", Bye !");
// Doesn't work : listener references original (not bounded) function
ev.target.removeEventListener(ev.type, listener);
// Who am I ?? ;-)
} else {
console.log("<bounded> still waiting for " +s + " " + new Date());
}
}
window.addEventListener('load', function(){
i = document.querySelector('input');
i.addEventListener("change",listener.bind(i,"abc"));
i.addEventListener("change",listener.bind(i,"def"));
});
我寫了這個醜陋的解決方法:
function autoRefBind(f, ...args){
var o = {};
o.me = f.bind(o,...args);
return o.me;
}
function listener(s,ev){
"use strict";
if (ev.target.value == s){
console.log("<bounded> I found " + s+ ", Bye !");
ev.target.removeEventListener(ev.type, this.me);
} else {
console.log("<bounded> still waiting for " +s + " " + new Date());
}
}
window.addEventListener('load', function(){
i = document.querySelector('input');
i.addEventListener("change",autoRefBind(listener,"abc"));
i.addEventListener("change",autoRefBind(listener,"def"));
});
但它很醜陋......: '這個' 必須是這個 「愚蠢」 的對象{我:}
錯在何處? –