2015-09-13 44 views
-1
<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> 

我很想知道为什么当我要求sayYourPower时我得到'undefined'...这是为了在方法结束时不包括“()”?javascript测试中的简单原型

+1

您将函数添加到'Person'原型,但是从'Superheroe'创建对象。并且即使你将'Person'改为'Superheroe'也不行,因为在你的情况下'this this'里面的事件处理器并不是指对象'超级英雄' – Grundy

+0

我犯了一个错误对不起! –

回答

0

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

0

这是应该的

<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> 
+0

您在添加处理程序之前调用'sayYourPower',因此onclick会附加结果此函数 - _undefined_ – Grundy

+0

您是否测试了这个?另外,你认为OP在“人”课上试图做什么?你的答案如何解决? –

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()});
<div id="id1">Click to know</div>