Why are instance properties updated when the prototype is updated if the property was not set by the instance itself?

Why are the properties of an instance that stores primitive values, not references, updated when the prototype is updated if the property was not set by the instance itself?

Let me give an example:

var Obj = function () {};
Obj.prototype.num = 1;

var myObj = new Obj();
var myOtherObj = new Obj();
console.log(myObj.num); //logs 1
console.log(myOtherObj.num); //logs 1

//After instances are created they still share the value (which is strange):
Obj.prototype.num = 3;
console.log(myObj.num); //logs 3
console.log(myOtherObj.num); //logs 3

//Update one of the instances property
myObj.num += 2;
console.log(myObj.num); //logs 5
console.log(myOtherObj.num); //logs 3

//Here it gets weird:
Obj.prototype.num = 4;
console.log(myObj.num); //logs 5 not updated
console.log(myOtherObj.num); //logs 4 updated

A couple of weird things here:

After creating the instance, updating the class definition updates the value of the instance if and only if it has never been updated by the instance itself.

, , num, , , ( this.num instanceName.num) .

, ECMA5:

prototype [[Prototype]] , Function .

, internal [[Prototype]], . , , , , , , , .

+3
3

, , , , , .

, , num , , ( .num instanceName.num), instance.property .

. , , delete:

delete myOtherObj.num;

myOtherObj num .

, , , [[Prototype]] . , [[Prototype]] Javascript.

, "prototype" "" [[Prototype]] , , .


:

function Obj() {};
Obj.prototype.num=1;

var myObj = new Obj();
console.log(myObj.num); // logs 1

Obj.prototype = {num:3}; // replaces Obj.prototype
console.log(myObj.num); // logs 1

var myOtherObj = new Obj(); 
console.log(myOtherObj.num); // logs 3
console.log(myObj.num); // still logs 1

, , , . - .

+4

, .;)

, , JS- . , .

, , , .

, . .

:

Obj.prototype.num = 3;
console.log(myObj.num); //logs 3
console.log(myOtherObj.num); //logs 3

Obj.prototype.num.

myObj.num += 2;

Obj.prototype.num myObj.num.

Obj.prototype.num = 4;
console.log(myObj.num); //logs 5 not updated
console.log(myOtherObj.num); //logs 4 updated

myObj.num Obj.prototype.num .

+3

, , SO, . , .


. , , num, ( - ) .

, , . , , , .

, , "" . , , .


EDIT: . 4.3.4 4.3.5 , 5- .

4.3.4

, . "prototype" , .

4.3.5

.

. , "prototype" . "prototype" program.prototype, , , , . , Object.create.

+2
source

Source: https://habr.com/ru/post/1774179/


All Articles