Why doesn't changing the prototype affect previously created objects?

I have the following code:

var A = function() {};
var a = new A();
var b = new A();
A.prototype.member1 = 10;

A.prototype = {}
var c = new A();
console.log(a.member1);
console.log(a.constructor === b.constructor);
console.log(a.constructor === c.constructor);
console.log('---------');
console.log(c.member1);

At the exit:

10
true
false
---------
undefined
undefined

Prototype aand bhas not changed, and c- a new one. Was this right due to what is a.constructornot equal c.constructor, and each of them has prototype? Are there any other loops where the constructors of two objects may not be equal?

Additional question: why were two lines printed undefined? (Chromium)

+5
source share
3 answers

At the time you call

var a = new A();

basically this assignment is fulfilled:

a.__proto__ = A.prototype;

Then you reassign A.prototypeto a new object, so it cgets {}as your prototype.

A.prototype = {};
var c = new A();

A.prototype - a.__proto__ .

, a.constructor c.constructor ?

.constructor - . .

: undefined?

, ! (Opera 12)

+5

, __proto__ . , a b :

var a = new A();
// a.__proto__ == A.prototype == {} (soon == {member1:10})
var b = new A();
// b.__proto__ == A.prototype == {} (soon == {member1:10})

A.prototype = {} // this changes A.prototype, but not a.__proto__ or b.__proto__
var c = new A(); // c.__proto__ = {}

undefined - c.member1. - , ,

+2

:

A.prototype = {}

When you get to this line of code, you actually create a BRAND NEW OBJECT in memory, which is {}. Creating any new objects using A as your constructor will point to this BRAND OBJECT as a prototype.

However, OLD PROTOTYPE still exists in memory. It is simply that A.prototype no longer points to this. Any objects created using A as a constructor, before overriding the prototype reference, still point to this OLD PROTOTYPE as a prototype.

+1
source

All Articles