Wednesday, July 27, 2011

javascript prototype only used for properties inheritance

Check this code:

function Person(name) {
                this.name = name;
}
Person.prototype.type = 'human';
var instance = new Person('henry');
console.log(instance.type); //this will be 'human'
console.log(Person.type); //this will be 'undefined'

It is a little confusing that why Person.type is 'undefined' while the instance of Person can have correct type. The explanation is this, quoted from http://www.mollypages.org/misc/js.mp:

"The prototype is only used for properties inherited by objects/instances created by that function. The function itself does not use the associated prototype."

No comments: