1
<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.
asked Dec 29, 2012 at 23:53
1
  • Object.prototype just allows you to extend the object from outside of it. Calling it still relies on an instance of said object being defined first. Commented Dec 29, 2012 at 23:59

2 Answers 2

4

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()
answered Dec 29, 2012 at 23:55
Sign up to request clarification or add additional context in comments.

Comments

2

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.

answered Dec 29, 2012 at 23:55

1 Comment

Can you lead me to a nice article on prototype where i can understand the concept fully.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.