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

I'm wonder why I'm getting 'undefined' when I ask for the sayYourPower...It is for not including the "()" at the end of the method?

Frnnd Sgz
  • 236
  • 1
  • 4
  • 19
  • 1
    you add function to `Person` prototype, but create object from `Superheroe`. and also even if you change `Person` to `Superheroe` it would not work, because in your case `this` inside event handler refers not to object `Superheroe` – Grundy Sep 13 '15 at 18:51
  • I make a mistake sorry! – Frnnd Sgz Sep 14 '15 at 06:55

3 Answers3

0

Your Superhero object is yet to extend the Person prototype, hence Mike doesn't have a function sayYourPower.

Matias Faure
  • 822
  • 1
  • 9
  • 20
0

This is how it should be

<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>
Md. Salahuddin
  • 1,062
  • 15
  • 22
  • you call `sayYourPower` before adding handler, so to onclick would be attach result this function - _undefined_ – Grundy Sep 13 '15 at 18:54
  • Did you test this? Also, what do you think the OP was trying to do with the "Person" class and how does your answer address that? –  Sep 13 '15 at 18:55
0

You should use Superheroe instead of Person, and also use bind function, or anonymous function as handler, for savinf context

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>
Grundy
  • 13,356
  • 3
  • 35
  • 55