Kevin
Kevin

Reputation: 23634

calling a method using prototype

<script>     
  var Kevin = function(){   
       this.name = 'kevin'
  }          
  Kevin.prototype.getKevin = function(){          
       alert(this.name);        
  }            
  Kevin.prototype.getKevin();

  function John(){
     this.name = 'john'
  }      
  John.getStaticJohn = function(){
     alert(this.name);    
  }

  John.prototype.getJohn();
  John.getStaticJohn();

</script>
  1. Why is that i am getting undefined in both the cases when calling the method using prototype.
  2. When i try to call the static method in John class, it prints the output perfectly.

Upvotes: 1

Views: 47

Answers (2)

Pointy
Pointy

Reputation: 413702

You're getting undefined because the prototype has no "name" property. Note also that your call to "getStaticJohn()" does not in fact "work perfectly" - it alerts "John" with a capital "J" because it's accessing the "name" property of the function object "John".

When you call a method via an expression of the form something.functionName, then the value of this inside the function will always be the value of something. Thus when you call

John.prototype.getJohn();

the value of this inside the "getJohn()" function will be John.prototype, and not any instance constructed by the "John()" constructor.

If you add this:

John.prototype.name = "John's prototype";

then your call to John.prototype.getJohn() will alert something other than undefined.

Upvotes: 2

David G
David G

Reputation: 96790

If you wanted to call the methods from the constructor, you would need to create an anonymous instance:

(new Kevin).getKevin(); // or new Kevin().getKevin()

Upvotes: 4

Related Questions