Why are objects with inherited objects accessible by the key, but "hidden"?

While playing with JavaScript (which is quite new to me), I discovered strange behavior:

var some_object = {
    foo: "bar",
    baz: "moo"
};

console.log(some_object); // { foo: 'bar', baz: 'moo' }

var inherited_object = Object.create(some_object);
console.log(inherited_object); // {} 
console.log(inherited_object.baz); // moo

The inherited object looks "empty", but its members are still accessible by key. What is going on here and what logic is behind this behavior?

+4
source share
4 answers

Here's how prototype inheritance works.

When you use Object.createto create a new object from an existing object, properties are inherited from the object from which the object is created. Thus, a newly created object may look empty, but it contains a reference to inherited properties from the parent.

__proto__ , .

, , , Object. Object, /.

_____________              _____________              ______________
|Own Members|       -----> |     foo    |          -->| toString() |
|           |       |      |     bar    |          |  |  valueOf() |
|           |       |      |            |          |  |            |
|___________|       |      |____________|          |  |            |
| __proto__ |-------|      |  __proto__ |-----...--   |            |
-------------              --------------             --------------

inherited_obj              some_obj                       Object

, , Object, .

, , __proto__.

+4

Javascript. , , Javascript , , , , , ...

console.log " " , Javascript __proto__, .

+3

2 :

  • Object.create

  • .

, Object.create.

Object.create ():

  • f
  • someobject (f.prototype = someobject)
  • return new f

inherited_object foo, bar.

, inherited_object, . .

+2
source

Because Object.create (...) uses some_object as a prototype of "inherited_object". This means that if you examine the inherited_object structure , the __ proto __ member points to some_object .

In javascript, if an element is not found directly in the object, its prototype searches for the same member. Therefore, you perceive them as "hidden"

+1
source

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


All Articles