This is the 17th day of my participation in the More text Challenge. For more details, see more text Challenge

The prototype

Why use prototypes

Using prototypes can improve code reusability.

Look directly at the following code to understand:

<script>
        function Person(name,age,gender){
            this.name = name;
            this.age = age;
            this.gender = gender;
            this.sayName = function () {

            }
        }
        var person1 = new Person();
        var person2 = new Person();
        console.log(person1.sayName == person2.sayName);
    </script>
Copy the code

You can see that the result is false, and that’s the downside of this approach. For every object created based on Person, these same methods are stored repeatedly, but they’re not essentially the same method, which is wasteful. This problem can be solved by using prototype objects to store common properties and methods.

How the prototype object is used

So how do you use prototype objects?

This object is called a prototype object by using the Prototype property to point to it. Use prototype objects to add new methods and properties to objects.

<script>
        function Person(name){
            this.name = name;
        }
        var person = new Person("Tom");
        Person.prototype.sayName = function () {
            console.log(this.name);
        };
        var person2 = new Person("Jack");
        console.log(person.sayName == person2.sayName);
        person.sayName();
        person2.sayName();
    </script>
Copy the code

As you can see, there is no sayName method in the original Person() constructor, and you can use Prototype to add properties and methods to the constructor.

inheritance

Use prototype objects to inherit. Inheritance is implemented if an object does not have a property or method originally, but can be obtained from another object.

<script>
        function Person(name){
            this.name = name;
        }
        Person.prototype.sayName = function () {
            console.log(this.name);
        };
        var person1 = new Person("Tom");
        var person2 = new Person("Jack");
        person1.sayName();
        person2.sayName();
    </script>
Copy the code

There is no sayName method in person1 and Person2, but you can add the method to the Person stereotype so that both objects have it. The above code can be interpreted as an object that inherits members from the prototype object.

This is not the only way to inherit in JS. Next time we will look at other inheritance methods in JS.

This is my understanding of the JS prototype, if any errors or shortcomings are welcome to comment. (Writing is not easy, welcome to like.)