1

Possible answer, but answer shows what's observed but doesn't explain why it happens that way.

Let's create three function constructors.

function A() {
}

function B() {
}

function C() {
}
C.prototype.nm = "C";
B.prototype = new A()
var obj = new B()
B.prototype = new C()
console.log(obj.nm); // prints, undefined.

So after the last line I was expecting 'obj' to receive properties from prototype of C but it's not. So does it mean that once the object is created it is tied to whatever prototype it was assigned during creation ? Why is it that way, I mean I can receive live updates to object through the prototype but wouldn't it be better if can get updates from multiple objects just changing constructors prototype property ?

Community
  • 1
  • 1
coder7891
  • 151
  • 9
  • "wouldn't it be better if can get updates from multiple objects just changing constructors prototype property" --- nope, it wouldn't be. – zerkms Mar 01 '15 at 20:09
  • @zerkms, so once the object is created, it is tied to a particular prototype and will only receive updates from that prototype and nothing else. – coder7891 Mar 01 '15 at 20:15
  • and that's great. It's how predictable code should behave. – zerkms Mar 01 '15 at 20:56

2 Answers2

0

You do not assign B any specific prototype properties so the inheritance chain is broken.

Jack Shultz
  • 2,031
  • 2
  • 30
  • 53
0

Does it mean that once the object is created it is tied to whatever prototype it was assigned during creation ?

Yes, exactly. Objects inherit properties from the object in their [[Prototype]] internal property.

That property is set when you create the instance:

13.2.2 [[Construct]]

  • Let proto be the value of calling the [[Get]] internal property of F with argument "prototype".
  • If Type(proto) is Object, set the [[Prototype]] internal property of obj to proto.

But if you change the prototype property of a constructor, it won't affect previous instances.

In fact, prototype is not special by itself, it's just that [[Construct]] internal method uses it while creating instances.

once the object is created it is tied to whatever prototype it was assigned during creation ?

Mostly yes. You can change it, but is not recommended (because of performance issues), using:

  • __proto__: this was a non-standard property in Object.prototype which could be used as a getter or setter of [[Prototype]]. ECMAScript 6 standardized it in Annex B (Additional ECMAScript Features for Web Browsers).

  • Object.setPrototypeOf, a new method introduced by ECMAScript 6.

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • Yeah, tested it. '__proto__' can be used to change the prototype of a object to something else. But it is changing the 'constructor' property. That's strange. – coder7891 Mar 01 '15 at 20:37