javascript测试中的简单原型 点击了解 功能超级英雄(电源){ 这个。力量=力量; } //已编辑:已解决复制错误 Superheroe.prototype.sayYourPower=function(){ 警惕(“这是我的力量:”+这。力量); } var Mike=新的超级英雄(“快速编码”); document.getElementById('id1')。addEventListener(“单击”,Mike.sayYourPower);

javascript测试中的简单原型 点击了解 功能超级英雄(电源){ 这个。力量=力量; } //已编辑:已解决复制错误 Superheroe.prototype.sayYourPower=function(){ 警惕(“这是我的力量:”+这。力量); } var Mike=新的超级英雄(“快速编码”); document.getElementById('id1')。addEventListener(“单击”,Mike.sayYourPower);,javascript,Javascript,我想知道为什么当我问sayYourPower时我会变得“未定义”…这是因为在方法的末尾没有包含“()”?你的超级英雄对象还没有扩展Person原型,因此Mike没有函数sayYourPower <div id="id1">Click to know</div> <script> function Superheroe(power){ this.power=power; } //edited: copy mistake solved Superhero

我想知道为什么当我问sayYourPower时我会变得“未定义”…这是因为在方法的末尾没有包含“()”?

你的超级英雄对象还没有扩展Person原型,因此Mike没有函数
sayYourPower

<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>
点击了解
功能超级英雄(电源){
这个。力量=力量;
}
Superheroe.prototype.sayYourPower=function(){
警惕(“这是我的力量:”+这。力量);
}
var Mike=新的超级英雄(“快速编码”);
document.getElementById('id1').addEventListener(“单击”,Mike.sayYourPower.bind(Mike));

对于savinf上下文,您应该使用
超级英雄
而不是
人物
,还应该使用
绑定
函数或匿名函数作为处理程序

功能超级英雄(电源){
这个。力量=力量;
}
Superheroe.prototype.sayYourPower=function(){
警惕(“这是我的力量:”+这。力量);
}
var Mike=新的超级英雄(“快速编码”);
document.getElementById('id1').addEventListener(“单击”,Mike.sayYourPower.bind(Mike));
//另一个带有匿名函数的变体
//document.getElementById('id1').addEventListener(“单击”,函数(){Mike.sayYourPower()})

点击了解
您将函数添加到
人物
原型,但从
超级英雄
创建对象。而且,即使您将
Person
更改为
superhero
,它也不会工作,因为在您的情况下,
内部事件处理程序不是指对象
superhero
我犯了一个错误,对不起!在添加处理程序之前调用
sayYourPower
,所以onclick将是attach result this function-undefinedded,您测试了这个吗?另外,你认为OP试图对“Person”类做什么?你的答案如何解决这个问题?
<div id="id1">Click to know</div>

<script>
  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));
</script>