7 modes for JavaScript to create objects

Source: Internet
Author: User

Create a student object using the literal method:

1 var function () {2         name: "Redjoy",3         age:21,4        sex: Women,5         function() {6                  alert (this. name); 7         }8 };

Add attributes to an object using the Object.defineproperties () method: (Only ie9+,ff4+,sf5+,op 12+,chrome support)

1 varStudent = {};2 object.defineproperties (student,{3 name:{4Value: "Redjoy"5         },6 age:{7Value:218         },9 _year:{Tenvalue:2015 One         }, A year:{ -Getfunction(){ -                     return   This. _year; the             }, -Setfunction(newvalue) { -                     if(NewValue > 2015){ -                              This. _year =newvalue; +                              This. Age + = newValue-1993; -                     } +              } A          } at});

When creating a single object using the object constructor and the literal, we create a lot of duplicate code by creating many objects using the same interface. So, there are seven modes of creating objects:

First, the factory model (abstract the process of creating specific objects)

1 functioncreatestudent (name,age,sex) {2         vars =NewObject ();3S.name =name;4S.age =Age ;5S.sex =sex;6S.sayname =function (){7Console.log ( This. Name);8         };9         returns;Ten } One  A varStudent1 = Createstudent ("Redjoy", +, "women"); - varStudent2 = Createstudent ("Jonny", "N", "Man");

Second, the structural function mode

Rewrite The example above:

1 functionStudent (name,age,sex) {2          This. Name =name;3          This. Age =Age ;4          This. Sex =sex;5          This. Sayname =function() {6Console.log ( This. Name);7         };8 }9 Ten varStudent1 =NewStudent ("Redjoy", +, "women"); One varStudent2 =NewStudent ("Jonny", "a", "man");

In contrast to Factory mode, the constructor pattern can label its instances as a specific type.

Third, prototype mode

1 functionStudent () {2}//constructor Function3 4Student.prototype = {5Name: "Redjoy",6Age:21,7Sex: "Women",8Sayname:function(){9Console.log ( This. Name);Ten         } One }; A  - varStudent1 =NewStudent (); - varStudent2 =NewStudent ();

Iv. combining the constructor pattern with the prototype pattern (the most common way)

Pros: The constructor pattern is used to define instance properties, and the prototype pattern is used to define methods and shared properties, each with its own copy of the instance properties, but also with a reference to the method, which maximizes memory savings.

1 functionStudent (name, age, sex) {2          This. Name =name;3          This. Age =Age ;4          This. Sex =sex;5}//defining instance properties in constructors6 7Student.prototype = {8 Constructor:student,9 sayname:funtion () {TenConsole.log ( This. Name); One         }    A}//defining the constructor attribute and the Sayname () method in the prototype -  -  the varStudent1 =NewStudent ("Redjoy", +, "women"); - varStudent2 =NewStudent ("Jonny",%, "man"); -  -Console.log (Student1.sayname = = = Student2.sayname);//true

Five, dynamic prototype mode

Pros: Encapsulates all information in a constructor, while preserving the benefits of constructors and prototypes by initializing the prototype in the constructor (only if necessary).

1 functionStudent (name, age, sex) {2            //Properties3             This. Name =name;4             This. Age =Age ;5             This. Sex =sex;6            //Method7            if(typeof  This. sayname! = "function"){8Student.prototype.sayName =function(){9Console.log ( This. Name);Ten                 }; One             } A } - varStudent =NewStudent ("Redjoy", +, "women"); -Student.sayname ();

Note: You cannot use object literals to rewrite prototypes when using dynamic prototype mode.

Vi. Parasitic structural function patterns

1 functionStudent (name, age,sex) {2         vars =NewObject ();3S.name =name;4S.age =Age ;5S.sex =sex;6S.sayname =function(){7Console.log ( This. Name);8         };9         returns;Ten } One  A varStudent =NewStudent ("Redjoy", +, "women"); -Student.sayname ();//"Redjoy"

Seven, the SAFE structure function pattern

Secure object: Refers to an object that does not have an announcement attribute and whose method does not refer to this.

Similar to the parasitic constructor pattern, but there are two different points:

1. Instance methods for newly created objects do not use this

2. Do not want the new operator to call the constructor

Rewrite The example above:

1 functionStudent (name, age, sex) {2         //to create an object to return3         vars =NewObject ();4         //You can define private variables and functions here similar to the above5         //Add Method6S.sayname =function(){7 Console.log (name);8         };9 Ten         //return Object One         returns; A}

You can choose a method that suits you according to the schema of each object you create, creating a function

(above as your own personal note, reference from JavaScript Advanced Programming third edition)

7 modes for JavaScript to create objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.