This example describes the usage of JavaScript prototype patterns. Share to everyone for your reference. The specific analysis is as follows:
After understanding the drawbacks of the factory model and the constructor pattern, we know why we need the prototype model.
Definition of prototype mode I: Each function has a prototype (prototype) attribute, which is an object that contains properties and methods that can be shared by all instances of a particular type. For example, in the constructor model Sayinformation () method, if the declaration two instances to construct two times Sayinformation method, but the declaration two times is not necessary, this is why there is a prototype model of the appearance (NI, online blogs above all are talking about things, Or reading a book is easy to understand), sayinformation () declared as a prototype mode, the instance is shared, there is no need to declare twice
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The |
" "" "function person () {} Person.proto Type.name= "Jack"; person.prototype.age=10; Person.prototype.sayinformation=function () {console.log ("My Name is" +this.name+ "The Age is" +this.age);} var person1 = new P Erson (); Person1.sayinformation (); Console.info (Person1.name); Attribute name person1.name= "Greg" from the prototype; Modifies the instance's Name property Console.info (Person1.name); The property name Delete person1.name from the instance; Properties from the instance, where the properties of the instance are deleted, but the properties of the stereotype still exist console.info (person1.name); Attribute name var person2 = new Person () from the prototype; Person2.sayinformation (); Console.info (Person1.hasownproperty ("name")); hasOwnProperty check whether the property belongs to an instance or a prototype and returns True Console.info (Person1.name==person2.name) in an instance; Console.info (person1.sayinformation==person2.sayinformation); Console.info (Person1.constructor); The constructor//prototype pointing to Person1 is simpler to spell function Person2 () {} Person2.prototype={Name: "Jack", Age:29, Sayinformationfunction:function () {console.log (' My name is ' +this.name+ ' age is ' + This.age); } } |
The
wants this article to help you with your JavaScript programming.