When I first came into contact with this prototype I refused, I still spent a part of my time understanding this thing, not proficient, what questions to reply to below
After all, I was used to the bricks (funny);
As I understand it, prototype is nothing more than a function of two foundations:
1. Dynamically adding properties and methods of a class
2. Copying the contents of the original class
Let's take a look at the first one:
The first is to define a simple person class;
var person = function (name,age) {
Specifies that the property of the class is a parameter value
THIS.name = name;
This.age = age;
Specify a talk method for the class
This.talk = function () {
Alert ("Talk");
};
};
Let's create an instance of the person
var Zhangsan = new Person ("Zhangsan", 19);
var lisi = new Person ("Lisi", 19);
1
2
So we have two instances of the person, Zhangsan and Lisi, there is a method talk in the person, and when we generate the instance, the talk will be generated again, so this is extremely bad, because if we want to produce an instance of 100 person, The talk () will be created 100 times, which is likely to cause a memory overflow. There is no way to create only one talk (), the answer is YES! Just use prototype!.
Take a look at the code first:
The same class that defines a person
var person = function (name,age) {
Specifies that the property of the class is a parameter value
THIS.name = name;
This.age = age;
We don't set the talk method for person here anymore.
};
};
To generate an instance of person again
var Zhangsan = new Person ("Zhangsan", 19);
var lisi = new Person ("Lisi", 19);
After the creation here, we learned that Zhangsan and Lisi have no talk method, we now use prototype to add
Person.prototype.talk = function () {
Alert ("Talk");
};
At this point, all instances of person have this method
Zhangsan.talk ();//"Talk"
Lisi,talk ();//"Talk"
Now that the first use is clear, let's look at the second use.
The second use is to copy the contents of the original class.
Create a new class Person2
var Person2 = function (name,age) {};
Person2.prototype = new Person ();
The contents of the person at this time have all been copied into the Person2.
JAVASCRIPT-JS's prototype prototype understanding explanation