0

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.

Fratt
  • 239
  • 3
  • 13
  • This question should probably be "I don't quite understand how the `new` keyword works in JS" -- to see a very detailed description, see: http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – David Titarenco Aug 19 '14 at 00:53
  • what does "foo = foo || {}" do? – dandavis Aug 19 '14 at 01:51
  • The question could probably be phrased many ways; however, I believe your reference to the other question helped to clarify. It's the first reference of many I've seen actually calling out the internal nature of the new object's prototype. – Fratt Aug 19 '14 at 02:13

2 Answers2

0

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

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160
0

Object instance not have prototype property .But instance has proto property hold the reference of prototype property.

consider below example:

var Person = function(name){
  this.name = name;
};
Person.prototype.walk=function(){
  this.step().step().step();
};
var bob = new Person("Bob");

See the generated proto property for bob instance

tsb
  • 1