2 回答
TA贡献1853条经验 获得超9个赞
第一个问题
这只是一个错字,你是在打电话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>
TA贡献1786条经验 获得超13个赞
回答最初的问题:修复错字适用于您的内联事件
回答第二个问题 - 如何使用 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/>
尝试找到如何this在使用 addEventlListener而不包装在函数中时保留原型。
注意按钮 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/>
添加回答
举报
