First code:
function Human () {}
Human.prototype.name = "Genghis Khan";
Human.prototype.sex = "male";
Human.prototype.say = function () {
alert (this.name);
var man = new Human ();
Man.say (); Genghis Khan
var woman = new Human ();
Woman.say (); Genghis Khan
alert (Man.say = = Woman.say);//true
Prototype is one of the very core points of knowledge in JavaScript. He is an important part of the object-oriented thinking in JavaScript.
Let's see where prototype is, with so much power.
Each function in JS has a prototype attribute, which we call a prototype. (This explanation is a bit rotten, equal to not say, no way, do not know how to give him the definition of ^_^);
One of the benefits of using a prototype object is to have all instances share the same properties and methods on the prototype.
In the example above, Name,sex,say are all located on prototype, so man and woman share these properties and methods. Although there are 2 instances in memory, they have only one copy of name and sex and say.
This is a great memory saver in a complex project.
Also because of this, the prototype model is better than the constructor pattern described in the previous section.
This simple prototyping model shows a lot of unrealistic things at one glance:
1. Since all the properties and methods are shared, is it enough that I instantiate an object?
2. Each object is an individual (has its own specific attributes or methods), but also has similarities (common attributes and methods),
Then there is the result of the interaction between the constructor pattern and the prototype pattern. This combination pattern continues in the next chapter.