2

Why prototype function is not called .. when image is clicket?

Html Code :--

    <!DOCTYPE html>
    <html style="height: 100%;">
    <head>
      <script type="text/javascript" src="tt.js"></script>
    </head>
    <body>

    <p>This example calls a function which performs a calculation, and returns the result:</p>

    <p id="demo"></p>

    <input type="image" src="http://t2.gstatic.com/images?q=tbn:ANd9GcSTcJA5J-LOj0HOP1ZMzdSQIsxwuguFdtlesHqzU15W8TXx232pFg" onclick="myFunction('Info clicked')"/>

   <script>
     var a = new myFunction();
     document.getElementById("demo").innerHTML = a.k;
    </script>

    </body>
    </html>

java script :--

function myFunction(l) {
    this.k = "hello";
    alert(this.k);

    var t = this.temp(l);
    alert(t);


}

myFunction.prototype.temp = function(a)
{
    alert(a);

    return 10;
}

If i put inside html page body it works :--

<script>
var a = new myFunction();
document.getElementById("demo").innerHTML = a.k;
</script>
Katoch
  • 2,709
  • 9
  • 51
  • 84
  • `myFunction` is a constructor and needs to be invoked with `new`! – Bergi Aug 14 '14 at 10:43
  • Seems you are confusing [input](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input) with [img](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Img), input has no src attribute. – rafaelcastrocouto Aug 14 '14 at 10:46
  • @rafaelcastrocouto — http://www.w3.org/TR/html4/interact/forms.html#adef-src – Quentin Aug 14 '14 at 11:07
  • console.log is far better than alert (if you're not using IE). It'll log objects so you can inspect them (with Firefox I prefer Firebug). For an explanation about constructor functions and prototype you can see this answer: http://stackoverflow.com/a/16063711/1641941 – HMR Aug 14 '14 at 12:26
  • Thx Quentin ... I did not knew about that! – rafaelcastrocouto Aug 14 '14 at 20:34

2 Answers2

1

Because you are calling this.temp() on the constructor function and not on an instance of it.

You need to create an instance with new.

new myFunction('Info clicked')

Note that this doesn't make sense. If you want to do things when the constructor runs, you should assign the methods to the constructor and not the prototype.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • What do you mean, "on the constructor"? – Bergi Aug 14 '14 at 10:44
  • @Bergi — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new – Quentin Aug 14 '14 at 10:45
  • Without `new`, `this` is not the constructor, and with `new` it's neither. So what do you mean? Calling a method of the instance from within the constructor is fine in general. – Bergi Aug 14 '14 at 11:51
0

If you want to stick to your javascript definition, all you need to do to solve this problem is to change the attribute onClick on your html code to new myFunction("...");

<input type="image" src="http://..." onclick="new myFunction('Info clicked')"/>
Khalid
  • 4,730
  • 5
  • 27
  • 50