We know that JS has objects, for example

var obj = { name: 'obj' } 
Copy the code

We can do a few things to OBj, including

  • Read property
  • New property
  • Update property
  • Delete property

Let’s focus on the “read” and “new” properties.

Prototype and prototype chain

Before we do anything else with obj, we find that obj already has several properties (methods) :

That is:

Console. dir(obj) :

  1. Obj itself has a property name (this is what we added to it)

  2. Obj also has a property called __proto__ (which is an object)

  3. Obj.__proto__ has many attributes, including valueOf, toString, constructor, etc

  4. Obj.__proto__ actually has a property called __proto__ (not shown in console.log) with a value of null

Now back to our question: why does obj have valueOf/toString/constructor?

The answer:

This has to do with __proto__.

When we “read” obj.toString, the JS engine does the following:

  1. See if the obj object itself has a toString attribute. No go to the next step.

  2. Obj.__proto__ has toString. Obj.__proto__ has toString

    So obj.tostring is actually obj.__proto__.tostring found in step 2.

    As you can imagine,

  3. If obj.__proto__ does not, then the browser will continue to look at obj.__proto__

  4. If obj. __proto__. __proto__ also have no, the browser will continue to check the obj… __proto__. __proto__. Proto__

  5. Until toString or __proto__ is found null.

The above procedure is the “search procedure” for the “read” property.

And this “search process” is connected by a chain of __proto__.

This chain is called a prototype chain.

Shared prototype chain

Now we have another object

var obj2 = { name: 'obj2' }
Copy the code

As shown in figure:

thenobj.toStringobj2.toStringIt’s actually the same thingobj2.__proto__.toString.

What’s the point of that?

If we overwrite obj2.__proto__. ToString, then obj. ToString will also change!

So obj and obj2 are objects that have some of the same behavior, and that’s what makes sense.

differentiation

What if we want obj.toString to behave differently from obj2.toString?

Just assign it:

Obj. toString = function(){return 'new toString method'}Copy the code

Conclusion:

  • The “read” property searches along the prototype chain.

  • The prototype chain is not looked at when a property is “added” (although if you add some configuration to the property, it is different).

Important formula

JS formula

Object.__proto__ === its constructor. Prototype

Root cause

Object. Prototype is the (direct or indirect) prototype of all objects

Function of justice

All functions are constructed by Function

  • __proto__ === function.prototype
  • Any function hasObject / Array / Function

The resources