JavaScript prototype chain

I study prototype chains in JavaScript and wrote a demo, but I can not understand the result.

This is my demo:

function A(){}
const c = new A();
A.prototype.sex = "girl";
A.prototype={
  name:"q",
  age:12
};
console.log(A.prototype.name);
console.log(c.name);
console.log(c.sex);

This is the conclusion:

"q"
undefined
"girl"

Why the conclusion console.log(c.name) undefined?

+4
source share
3 answers

A - your constructor, this means that you have added to this function everything you need to execute on the newly created object when you "initialize" it

in your case you are not doing anything. the constructor has a prototype property, which is an object that the entire object that you create with new A(), inherits from

unless you explicitly set a prototype for your constructor, so your default prototype is empty.

: const c = new A(); c :

A.prototype.sex = "girl";

"girl"

( ), , "". , c - , :

A.prototype={
  name:"q",
  age:12
};

A, A.prototype, . , ,

{
      name:"q",
      age:12
    }

. c - ( ) .

: const d = new A(), d.name , d.sex

, ( A.prototype), A.prototype, , "instanciated" .

+3

JavaScript.

5 6, .

, " .prototype A ". ", A.prototype new A()". c, , A .

new A() , .

  • obj - ECMAScript.
  • obj, 8.12.
  • [[Class]] obj "Object".
  • [[]] obj true.
  • proto [[Get]] F "prototype".
  • Type (proto) - Object, [[Prototype]] obj .
  • Type (proto) , [[Prototype]] obj , 15.2.4.
  • [[Call]] F, obj , [[Construct]] .
  • Type (result) - Object, .
  • obj.
+1

1)

2) ( ) sex

3) , c

So, ā€œAā€ is updated, but ā€œcā€ still gets the old prototype, so the name does not exist, but the gender property that was set before the prototype was changed exists, so you will find it.

0
source

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


All Articles