Katoch
Katoch

Reputation: 2777

javascript function object prototype

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>

Upvotes: 2

Views: 79

Answers (2)

Khalid
Khalid

Reputation: 4798

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')"/>

Upvotes: 0

Quentin
Quentin

Reputation: 943166

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.

Upvotes: 1

Related Questions