<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>
- Why is that i am getting
undefinedin both the cases when calling the method using prototype. - When i try to call the static method in John class, it prints the output perfectly.
2 Answers 2
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()
Comments
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.
Object.prototypejust allows you to extend the object from outside of it. Calling it still relies on an instance of said object being defined first.