var Person = function(name){
this.name = name;
};
console.log("1 " + typeof(Person.prototype)) //"object" - prototype is a property of a first class functional object
Person.prototype.sayhi = function(){console.log("hi")};
var john = new Person();
console.log("2 "+typeof(Person.sayhi)) // "undefined"
console.log("3 "+typeof(john.sayhi))// "function"
I am trying to get a better understanding of javascript prototype.
I wonder why case 2 returns undefined, while case 3 returns “object” as it should.
I read up on other posts but can’t seem to find the answer. Thanks.
Functions attached to the prototype (
Person.prototype) are not accessible from a constructor (Person), that isPerson.sayhiis not trying to access the prototype at all.When you call a constructor (say
var p = new Person()),Person.prototypeis attached to the prototype chain of the created object (p), that’s why you can callp.sayhi(). However,sayhiis never attached to the constructor