Search code examples
javascriptprototype-chain

JavaScript prototype chain


I'm trying to better understand the relationship between object prototypes across different object instances created through the same constructor.

Say I have this:

(function(ns){
 ns.User = function(Id){
    this.Name = "Some Name for " + Id;
    this.Id = Id;
};

})(foo = foo || {});

foo.User.prototype = function(){
var getName = function(){return this.Name;}
return{
    getName:getName
};
}();

$(function(){

var approver = new foo.User("approver1");
alert(approver.getName()); //works fine, shows approver1

var approver2 = new foo.User("approver2");
alert(approver2.getName()); //works fine, shows approver2

approver.prototype.getName = function(){alert(this.Name + " modified");} //<- this doesn't work (why, if foo.User, approver, and approver2 are just js objects with the same prototype chain?)
approver.getName = function(){alert(this.Name + " modified another way");} //<-re-defined this way works but only for approver object, not it's prototype that came from foo.User
});

It's my understanding that approver's prototype should be the same as foo.User.prototype since it's constructed from foo.User. They reference the same prototype chain, right? Same with approver2, correct?

If they all reference the same prototype chain then what is it that's prohibiting me from modifying the prototype object through the approver object? It appears approver.prototype.getName is 'undefined' but approver.getName() is valid, which I don't get if getName is part of the object's prototype definition.

Does it have to do with the fact foo.User is a function object but approver/approver2 are not?

I'm clearly missing something in this relationship. Thanks.


Solution

  • Object instances do not have a prototype property. The prototype of their constructor is used to look up members that can't be found on the instance: Prototypical inheritance - writing up