Reputation: 23634
<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>
undefined
in both the cases when calling
the method using prototype.Upvotes: 1
Views: 47
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
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