<div id="id1">Click to know</div>
<script>
function Superheroe(power){
this.power=power;
}
//edited: copy mistake solved
Superheroe.prototype.sayYourPower=function(){
alert('This is my power :'+ this.power);
}
var Mike = new Superheroe ("Code fast");
document.getElementById('id1').addEventListener("click",Mike.sayYourPower);
</script>
我想知道为什么我会得到&#39; undefined&#39;当我要求sayYourPower时......不包括&#34;()&#34;在方法的最后?
答案 0 :(得分:0)
您的Superhero对象尚未扩展Person原型,因此Mike没有函数sayYourPower
。
答案 1 :(得分:0)
您应该使用Superheroe
代替Person
,并使用bind
函数或匿名函数作为处理程序,用于savinf上下文
function Superheroe(power){
this.power=power;
}
Superheroe.prototype.sayYourPower=function(){
alert('This is my power :'+ this.power);
}
var Mike = new Superheroe ("Code fast");
document.getElementById('id1').addEventListener("click",Mike.sayYourPower.bind(Mike));
//another variant with anonymous function
//document.getElementById('id1').addEventListener("click",function(){Mike.sayYourPower()});
&#13;
<div id="id1">Click to know</div>
&#13;