2 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個(gè)贊
第一個(gè)問(wèn)題
這只是一個(gè)錯(cuò)字,你是在打電話funct1而不是func1
第二個(gè)問(wèn)題(更新)
問(wèn)題是當(dāng)您以自己的方式添加偵聽(tīng)器時(shí): .addEventListener("click",proto.func1)
this將是被點(diǎn)擊的元素,而不是您的proto實(shí)例,要解決這個(gè)問(wèn)題,您可以將它包裝在另一個(gè)函數(shù)子句中,如下面的代碼片段。
function MyProto() {
this.valeur = "toto";
}
MyProto.prototype = {
func1: function() {
var t = document.createTextNode("func1 called ");
document.body.appendChild(t);
var br = document.createElement("br");
document.body.appendChild(br);
this.func2();
},
func2: function() {
var t = document.createTextNode("func2 called");
document.body.appendChild(t);
}
};
var proto = new MyProto();
document.getElementById("myButton2").addEventListener("click", function() {
proto.func1()
});
<button id="myButton1" onclick="proto.func1()">First Button</button>
<button id="myButton2">Second Button</button>

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
回答最初的問(wèn)題:修復(fù)錯(cuò)字適用于您的內(nèi)聯(lián)事件
回答第二個(gè)問(wèn)題 - 如何使用 addEventListener 和保留this:
安全解決方案 - 將調(diào)用包裝在事件處理程序中的函數(shù)中:
function MyProto(){
this.valeur = "toto";
}
MyProto.prototype = {
func1: function() {
var t = document.createTextNode("func1 called ");
document.body.appendChild(t);
var br = document.createElement("br");
document.body.appendChild(br);
console.log(this)
this.func2();
},
func2: function() {
var t = document.createTextNode("func2 called");
document.body.appendChild(t);
}
};
var proto = new MyProto();
document.getElementById("myButton1")
.addEventListener("click",() => proto.func1() )
.as-console-wrapper {
height: 125px;
opacity: 0.3;
}
<button type="button" id="myButton1">addEventListener now works</button>
<hr/>
嘗試找到如何this在使用 addEventlListener而不包裝在函數(shù)中時(shí)保留原型。
注意按鈕 2 顯示了我編寫的代碼,現(xiàn)在 OP 將其用于后續(xù)問(wèn)題
function MyProto(){
this.valeur = "toto";
}
MyProto.prototype = {
func1: function() {
var t = document.createTextNode("func1 called ");
document.body.appendChild(t);
var br = document.createElement("br");
document.body.appendChild(br);
console.log(this)
this.func2();
},
func2: function() {
var t = document.createTextNode("func2 called");
document.body.appendChild(t);
}
};
var proto = new MyProto();
document.getElementById("myButton2").addEventListener("click",proto.func1)
document.getElementById("myButton3").addEventListener("click", proto.func1.bind(proto))
.as-console-wrapper {
height: 125px;
opacity: 0.3;
}
<button type="button" id="myButton1" onclick="proto.func1()">Here <i>this</i> is the prototype</button>
<button type="button" id="myButton2">addEventListener has unexpected <i>this</i></button>
<button type="button" id="myButton3">addEventListener bound <i>this</i></button>
<hr/>
添加回答
舉報(bào)