about how JavaScript creates objects:1. Factory mode
1 functionCreateperson (name, age, job) {2 varo =NewObject ();3O.name =name;4O.age =Age ;5O.job =job;6O.sayname =function(){7Alert This. Name);8 }; 9 returno;Ten } One varPerson1 = Createperson ("Nicholas", "Software Engineer"); A varPerson2 = Createperson ("Greg", "Doctor");
Cons: No idea of object-oriented2. Constructor Mode
1 functionPerson (name, age, job) {2 This. Name =name;3 This. Age =Age ;4 This. Job =job;5 This. Sayname =function(){6Alert This. Name);7 }; 8 }9 varPerson1 =NewPerson ("Nicholas", "Software Engineer");Ten varPerson2 =NewPerson ("Greg", "Doctor"); OnePerson1.sayname ();//"Nicholas" APerson2.sayname ();//"Greg"
Cons: 1. Each method in the constructor is recreated once the instance is created, this.sayname = new Function () {alert (this.name);};alert (Person1.sayname = = Person2.sayname); False3. Prototype Mode
1 functionPerson () {2 }3Person.prototype.name = "Nicholas";4Person.prototype.age = 29;5Person.prototype.job = "Software Engineer";6Person.prototype.sayName =function(){7Alert This. Name);8 };9 varPerson1 =NewPerson ();TenPerson1.sayname ();//"Nicholas" One A varPerson2 =NewPerson (); -Person2.sayname ();//"Nicholas" - theAlert (Person1.sayname = = Person2.sayname);//true
Pros: The properties and methods of an object are shareddisadvantage: Object properties need to be re-assignedunderstanding of Prototype objects:prototype and prototype relationships: Prototype (prototype is a property of a constructor) is a pointer to a prototype, and the constructor attribute in the prototype points to the original constructor. Person.prototype points to the prototype object, Person.prototype.constructor points to person4. Combination of construction mode and prototype mode
1 functionPerson (name, age, job) {2 This. Name =name;3 This. Age =Age ;4 This. Job =job;5 This. Friends = ["Shelby", "Court"];6 }7Person.prototype = {8 Constructor:person,9Sayname:function () {TenAlert This. Name); One } A }; - - varPerson1 =NewPerson ("Nicholas", "Software Engineer"); the varPerson2 =NewPerson ("Greg", "Doctor"); - -Person1.friends.push ("Van"); - +alert (person1.friends);//"Shelby,court,van" -alert (person2.friends);//"Shelby,court" +Alert (person1.friends = = = Person2.friends);//false AAlert (Person1.sayname = = = Person2.sayname);//true at
Pros: Attributes are defined in constructors, constructor and functions are defined in prototypes
JavaScript Advanced Programming Reading notes OOP