第一个问题
那只是一个错字,您打电话给funct1
而不是func1
第二个问题(更新)
问题是当您以自己的方式添加侦听器时:
.addEventListener("click",proto.func1)
this
将是被单击的元素,而不是您的proto
实例,要解决此问题,您可以将其包装在另一个函数子句中,例如下面的代码片段。
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>
,
回答第一个问题:修正内联事件中的错字
正在回答的第二个问题-如何使用addEventListener并保留this
:
安全解决方案-在事件处理程序中的函数中包装调用:
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/>
尝试查找在函数中使用addEventlListener WITHOUT 时如何保留原型this
。
注意按钮2显示了我编写的代码,OP现在将其用于后续问题
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/>
本文链接:https://www.f2er.com/3123045.html