This article mainly introduces the usage of the javascript prototype mode, and analyzes in detail the principles and usage skills of the javascript prototype mode in the form of examples, for more information about the javascript prototype, see the following example. Share it with you for your reference. The specific analysis is as follows:
After learning about the disadvantages of the factory mode and constructor mode, you can see why the prototype mode is required.
Definition of prototype mode I: each function has a prototype attribute, which is an object, its purpose is to include attributes and methods that can be shared by all instances of a specific type. For example, in the constructor model, if the sayInformation () method is declared, it is necessary to construct the sayInformation method twice, but it is unnecessary to declare it twice, this is why Nima, those blogs on the Internet are talking about things, or reading books is easy to understand. After sayInformation () is declared as a prototype, the instance is shared, so there is no need to declare it twice.
Function Person () {} Person. prototype. name = "jack"; Person. prototype. age = 10; Person. prototype. sayInformation = function () {console. log ("my name is" + this. name + "age is" + this. age);} var person1 = new Person (); person1.sayInformation (); lele.info (person1.name); // nameperson1.name = "Greg" from the prototype "; // modify the Instance name attribute lele.info (person1.name); // namedelete person1.name from the instance attribute; // The attribute from the instance is deleted here, however, the prototype attributes still have lele.info (person1.name); // The prototype attributes namevar person2 = new Person (); person2.sayInformation (); console.info (person1.hasOwnProperty ("name ")); // hasOwnProperty check whether the property belongs to the instance or the prototype. If the property belongs to the instance, trueconsole.info (person1.name = person2.name); lele.info (person1.sayInformation = person2.sayInformation); lele.info ); // point to the constructor of person1 // a simpler prototype of function Person2 () {} Person2.prototype = {name: "jack", age: 29, sayInformationfunction: function () {console. log ("my name is" + this. name + "age is" + this. age );}}
I hope this article will help you design javascript programs.