preface

Why study prototypes? What does a prototype chain do? This article explains to you through the diagram and code, quick to see ~ ~


Tip: The following is the text of this article, the following case for reference

What is a prototype?

JavaScript is a prototype-derived language that is different from other high-level languages, such as Java and C#

JavaScript is a dynamically weakly typed language. In short, you can think of everything in JavaScript as an object. In JavaScript, a stereotype is also an object.

Two, prototype chain

Each constructor has oneprototypeProperty points to the stereotype object, which passes throughconstructorRefers back to the constructor. Every object has a nonstandard property__proto__Is used to point to the prototype object. When the object looks for a member and cannot find it, it will follow__proto__Point to continue to look.

Three, code demonstration

Encapsulates an Array summation method, adds it to the prototype object of the built-in Array object, and then calls this method to sum.

The code is as follows (example) :

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <title>Document</title>
  </head>

  <body>
    <script>
      Array.prototype.sum = function () {
        return this.reduce((acc, cur) = > (acc += cur), 0)}let arr = [1.2.3.4.5]
      console.log('and:',arr.sum())

      console.dir(Array)
    </script>
  </body>
</html>

Copy the code

In the console output above, you can clearly see that we have added our own wrapped sum method to the built-in Array prototype. We have also completed the summation requirement by using the sum method on the built-in Array prototype. Learn waste again ~


conclusion

Learn over!!