current position:Home>JavaScript - prototype, prototype chain

JavaScript - prototype, prototype chain

2022-04-29 15:35:48The wind blows and the clouds fly

Write it at the front :

Many people can't tell __proto__ and prototype , Here is an example :

prototype It's a sum of money you earn from your own work , and __proto__ It's the money your father earns from working , When you were killed by your father new When I came out , His money is your money , But if you have brothers and sisters , They can also use your father's money , however prototype It's your own money , Your brothers and sisters can't use . In a nutshell , Your father ( Constructors ) Every time you create one children ( example ), Your father's own money (prototype: Your father is also human , His money belongs to him prototype) It's like you ( example ) Of __proto__

1. Preliminary understanding of prototype

      let arr = ["hello"];
      console.log(arr.concat("world"));

Here's the picture ,__proto__ The attribute is Array Prototypes of objects , because arr yes Array Instantiate the object , therefore arr You can also use Array The archetypal approach
 Insert picture description here

      let a = {
    };
      let b = {
    };

      console.log(Object.getPrototypeOf(a) === Object.getPrototypeOf(b));//true

2. Objects without prototypes

      let hq = {
     name: "hq" };
      console.log(hq.hasOwnProperty("name"));//true

      // Full data dictionary object 
      let obj = Object.create(null, {
    
        name: {
    
          value: "hello",
        },
      });
      console.log(obj);

 Insert picture description here
3. Prototype method and object method priority

      let hd = {
    
        render() {
    
          console.log("hd render");
        },
      };

      hd.__proto__.render = function () {
    
        console.log("hq");
      };
      
      hd.render();//hd render

* Use your own , No one will find it on the prototype

4. Function has multiple elders

      function User() {
    }
      console.dir(User)

 Insert picture description here
*prototype: Serve instantiated objects

      function User() {
    }

      User.prototype.show = function () {
    
        console.log("hello");
      };

      let hq = new User();
      console.log(User.prototype === hd.__proto__);//true

*proto: Serve function objects

      function User() {
    }

      User.__proto__.view = function () {
    
        console.log("user view");
      };

      User.view();//user view

* Functions can be used as constructors , It can also be used as a function object

5. Prototype relationship and attribute inheritance instance

      function User() {
    }
      
      console.dir(User.__proto__=== Function.prototype);//true

Code above , because User Actually by new Function Created , therefore User The prototype of the __proto__ Just === Function Of prototype

      User.prototype.__proto__ === User.__proto__.__proto__; //true

Code above , Let's first analyze User.prototype Namely User The prototype of the constructor itself , But this prototype prototype It's also an object in itself , And this prototype The of the object is actually through Object Constructed . We'll see User.proto, because User It's through new Function To the , therefore its __proto__ Is equal to Function.prototype. and Function Of prototype and User Of prototype It's all through Object Created objects , So their prototype __proto__ Equal
 Insert picture description here
6. Prototype of system constructor

      let arr = []; //new Array
      console.log(arr.__proto__ === Array.prototype);//true
      
      let str = ""; //new String
      console.log(str.__proto__ === String.prototype);//true

      let bool = true; //new String
      console.log(bool.__proto__ === Boolean.prototype);//true

      let reg = /a/i; //new RegExp
      console.log(reg.__proto__ === RegExp.prototype);//true

      let obj = {
    }; //new Object
      console.log(obj.__proto__ === Object.prototype);//true
      

Take a look at it.

        console.dir(Object.__proto__)

Output is as follows :
 Insert picture description here
A proper function
you 're right ,Object through Function Constructed .

7. Custom object prototype settings

* Set up prototypes :setPrototypeOf

      let obj = {
    };
      let parent = {
    name: "parent"};

      Object.setPrototypeOf(obj, parent);

 Insert picture description here
* Get the prototype :getPrototypeOf

      let obj = {
    };
      let parent = {
     name: "parent", age: 18 };
      Object.setPrototypeOf(obj, parent);
      console.log(Object.getPrototypeOf(obj));

 Insert picture description here
8. In the prototype constructor quote

* Through archetypal constructor You can find the constructor

      function User() {
    }
      console.log(User.prototype.constructor === User);//true
      function User(name) {
    
        this.name = name;
      }

      User.prototype = {
    
        constructor: User,
        show() {
    console.log(this.name)},
      };

      let ls = new User(" Li Si ");

      ls.show();// Li Si 

9. Create objects based on instances

Let's look at the following code first :

        function Admin() {
     }
        let obj = new Admin();
        console.log(obj.__proto__.constructor === Admin);//true

vernacular : Instantiate the prototype of the object __proto__ In the middle of constructor Property points to the constructor itself
Understand again :

      function User(name) {
    
        this.name = name;
        this.show = function () {
    
          console.log(this.name);
        };
      }

      let ls = new User(" Li Si ");

      function createByObj(obj, ...args) {
    
        // find obj Prototype constructor
        const constructor = Object.getPrototypeOf(obj).constructor;
        return new constructor(...args);
      }

      let zs = createByObj(ls, " Zhang San ");
      zs.show();

10. Prototype testing instanceof

  • a Whether there are prototypes on the object chain A Of this constructor prototype
        function A() {
     }
        let a = new A();
        console.log(a instanceof A)//true
        function A() {
     }
        function B() {
     }

        let b = new B();
        A.prototype = b
        let a = new A();

        console.log(a instanceof B)//true

11.Object.isPrototypeOf Prototype testing

        let a = {
    }
        let b = {
    }
        // b  Whether the object is in  a  Object's prototype chain 
        console.log(b.isPrototypeOf(a))//false
        console.log(Object.prototype.isPrototypeOf(a))//true
        // hold b Object is set to a Prototypes of objects 
        Object.setPrototypeOf(a, b)
        console.log(b.isPrototypeOf(a))//true

12.in And hasOwnProperty Detect the properties of
in: Detect whether an attribute exists in an object or the prototype chain of the object

        let a = {
     url: 'baidu.com' }
        let b = {
     name: 'baidu' }
        console.log('url' in a)//true
        Object.prototype.c = 'hello'
        console.log('c' in a)//true
        Object.setPrototypeOf(a, b)
        console.log('name' in a)

hasOwnProperty: Detect the current object , Do not check whether there is an attribute on its prototype chain

        let a = {
     url: 'baidu.com' }
        let b = {
     name: 'baidu' }
        Object.setPrototypeOf(a, b)
        console.log(a.hasOwnProperty('name'))//false
        let a = {
     url: 'baidu.com' }
        let b = {
     name: 'baidu' }
        Object.setPrototypeOf(a, b)
        for (const key in a) {
    //  Will traverse the attributes on the prototype chain 
            console.log(key)
        }

 Insert picture description here
utilize hasOwnProperty, Only traverse its own properties

        for (const key in a) {
    
            if(a.hasOwnProperty(key))
            console.log(key)
        }

Prototype testing :
instanceof: An object Whether or not there is Some constructor Of prototype
isPrototypeOf: An object Whether in Another object On the prototype chain

Property detection :
hasOwnProperty: testing The current object , Do not check whether there is... On its prototype chain An attribute
in: testing An attribute Does it exist in An object perhaps The prototype chain of the object On

13. Use call or apply Borrowing from the prototype chain

        let obj = {
     data: [1, 3, 2, 6, 5] }
        Object.setPrototypeOf(obj, {
    
            max() {
    
                return this.data.sort((a, b) => b - a)[0]
            }
        })

        let zs = {
    
            lessons: {
     js: 34, php: 53, node: 66 },
            get data() {
    
                return Object.values(this.lessons)
            }
        }
        console.log(obj.max.apply(zs))//66
        let obj = {
     data: [1, 3, 2, 6, 5] }
        Object.setPrototypeOf(obj, {
    
            max(data) {
    
                return data.sort((a, b) => b - a)[0]
            }
        })

        let zs = {
    
            lessons: {
     js: 34, php: 53, node: 66 },
        }

        console.log(obj.max.call(null, Object.values(zs.lessons)))//66

14.DOM Node borrowing Array Prototype method

<body>
    <button message='1' class="one">1</button>
    <button message='2'>1</button>

    <script>
        let btns = document.querySelectorAll('button')

        btn = Array.prototype.filter.call(btns, item => {
    
            return item.hasAttribute('class')
        })
        console.log(btn[0].innerHTML);//1
    </script>
</body>

15. Reasonable constructor method declaration

        function User(name) {
    
            this.name = name;
            this.show = function () {
    
                console.log(this.name)
            }
        }
        let ls = new User(' Li Si ')
        let zs = new User(' Zhang San ')

        console.log(ls);
        console.log(zs);

Object oriented , Save only object properties , about show Method does not need to open up independent memory, resulting in waste
 Insert picture description here
as follows , take show Method into the prototype

        function User(name) {
    
            this.name = name;
        }
        User.prototype.show = function () {
    
            console.log(this.name);
        }
        let ls = new User(' Li Si ')
        let zs = new User(' Zhang San ')

 Insert picture description here
16.this It has nothing to do with the prototype

        let obj = {
    
            name: ' Zhang San ',
            show() {
    
                console.log(this.name)
            }
        }
        Object.setPrototypeOf(obj, {
    })
        obj.show()// Zhang San 

No matter how the prototype is changed , our this Always point to the object that calls it

        let obj = {
    
            name: ' Zhang San ',
        }
        let User = {
    
            name: ' Li Si ',
            show() {
    
                console.log(this.name)
            }
        }
        Object.setPrototypeOf(obj, User)
        obj.show()//' Zhang San '

17.__proto__ Is a property accessor

* Strictly speaking __proto__ It's not an attribute , It is getter setter

      let obj = {
     name: " Zhang San " };

      obj.__proto__ = {
    
        show() {
    
          console.log(this.name);
        },
      };
      console.log(obj.__proto__);

 Insert picture description here
Above , We will obj Of __proto__ Set to another object ,ok, That's all right. , But look below

      let obj = {
     name: " Zhang San " };

      obj.__proto__ = {
    
        show() {
    
          console.log(this.name);
        },
      };
      obj.__proto__ = 99// a key 
      console.log(obj.__proto__);

( Not the same screenshot as above !)( Not the same screenshot as above !)
you 're right , Its output is the same as above , This is because it is a getter and setter , Its assignment operation is judged .

The meaning is as follows :

      let obj = {
    
        action: {
    },

        get proto() {
    
          return this.action;
        },
        set proto(value) {
    
          if (value instanceof Object) {
    
            this.actioin = value;
          }
        },
      };
      obj.proto = "abc";
      console.log(obj.proto);//{}

Above , Did not "abc" Set up the success , But set it as an object as follows , Then it can be set successfully

      obj.proto = {
    
        show: function () {
    },
      };
      console.log(obj.proto);

 Insert picture description here
The overlord bent his bow

      let obj = Object.create(null);
      obj.__proto__ = 99;
      console.dir(obj.__proto__);//99

adopt Object.create Let it not inherit Object The prototype of the , Orphan it , In this way, you can set its __proto__ attribute ( This is the attribute )

copyright notice
author[The wind blows and the clouds fly],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291415481435.html

Random recommended