Ways to create custom objects in JavaScript

Source: Internet
Author: User

This article references JavaScript Advanced Programming (3rd Edition) Chapter 6th: Object-Oriented Programming

The object is defined in ECMA-262 as: "A collection of unordered attributes whose properties can contain basic values, objects, or functions." "What I understand is that the object is a struct, and there are some basic properties of the struct and the methods of dealing with the structure, which encapsulate them as a whole." All objects in JS are created based on a reference type, which can be a native type, such as array,date, or it can be a developer-defined type.

The following is a summary of the JS in the creation of several models of objects, analysis of their respective advantages and disadvantages.

1. Factory mode
/****************** Factory mode *************************//*** use the same interface to create multiple objects, avoid code duplication, and use a function to encapsulate the details of creating objects with specific interfaces ***//***** Cons: Types of objects not recognized (all object types) ******/function Createperson (name, age, Job) {var object = new Object (); object.name = Name;o Bject.age = Age;object.job = Job;object.sayname = function () {alert (this.name);} return object;} var = createperson ("Jack", "Person1", "singer"), var person2 = Createperson ("Taylor", "a", "actor");

The Factory mode creates an interface function, creating a new object in an interface function, and defining properties and methods for it, calling this interface function for each creation of a new object. This pattern avoids the duplication of code that creates objects of the same type, but creates objects that are of type object and cannot represent the uniqueness of the custom type.

2. Constructor mode
/****************** the difference between the constructor pattern ***********************//**** and the Factory mode: ********************************//****1. Object ******************************//****2 is not explicitly created. Assigns properties and methods directly to the This object *******************//****3. No Return statement ********* Disadvantage: Each instantiation of an object creates a new function instance (the method function in the object) */function person (name, age, Job) {this.name = Name;this.age = Age;this.job = Job;this.sayname = function ()  //Each instantiation of an object creates a new function instance {alert (this.name);}} var person1 = new Person ("Jack", "a", "singer"), var person2 = new Person ("Taylor", "a", "actor");  Person is a specific type of instance

The constructor pattern also creates a function interface, but unlike Factory mode, this is not a normal function, but rather a constructor. There is no difference in definition between a constructor and a normal function, except that the constructor is called with a "new" in front of the function name. An object created with a constructor pattern has its own type name (such as the person in this example), but it still has a flaw: The method function in the object is not necessarily instantiated, it is better to define it once so that all objects of the same type are shared, and in this mode, each new object creates a new method function in the object. The code is not concise enough.

3. Prototype mode
/********************** prototype Mode ************************//**** prototype object allows all object instances to share the properties and methods it contains ********//**** Cons: All instances will get the same property value by default, with no attribute value of their own *****/function person () {}person.prototype.name = "Louis"; Person.prototype.age = "23"; Person.prototype.job = "Singer"; Person.prototype.friend = ["Harry", "Liam"]; Person.prototype.sayName = function () {alert (this.name);};       var person1 = new Person (), var person2 = new Person ();p erson1.age = "28";       Masks the Age property in the prototype object, but does not modify the properties in the prototype alert (person1.age);       28来 from the instance alert (person2.age);    23来 from prototype Person1.friend.push ("Zyan");    Modified an array of person1.friend references-attribute alert (person1.friend) in the prototype object;    "Harry,liam,zayn" alert (person2.friend); "Harry,liam,zayn" alert (person1.friend = = person2.friend)//True 

Whenever a new function is created, a Propotype attribute is created for the function based on a specific set of rules, which points to the prototype object of the function. at the same time, the prototype object also obtains a constructor property that contains a pointer to the new function. When the constructor is called to create a new instance, the inside of the instance will contain an internal pointer [[Propotype]], which points to the constructor's prototype object. Properties and methods in a prototype object can be shared by instances of all objects.

When you get the properties of an instance, search for the instance itself, that is, if there is no attribute in its constructor, and if there is one, return this value directly, and if not, continue searching for properties in the constructor's prototype object. So when you add a property or method that is already in a prototype to an object, the properties in the prototype are masked, but the properties in the prototype are not modified.

Sharing is the advantage of prototype mode, which avoids a lot of repetitive code, but also brings drawbacks. As in the example, a property of a reference type array is defined in the prototype object--friend,person1 instance adds an entry to the array, but because the friend attribute is also in Person2, the friend in Person2 is changed, This is not conducive to the uniqueness of each instance.

4. Combining the constructor pattern with the prototype mode
/**************** constructor pattern and prototype mode hybrid ********************//**** constructor mode is used to define strength attributes, and prototype patterns are used to define methods and shared properties ****//**** Each instance has its own copy of the instance properties, method sharing, saving memory *********/function person (name, age, Job) {this.name = Name;this.age = Age;this.job = Job; This.friend = ["Harry", "Liam"];} Person.prototype.sayName = function () {alert (this.name);} var person3 = new Person ("lious", "N", "singer"), var person4 = new Person ("Zyan", +, "Dancer");p Erson3.friend.push ("nail") ; alert (person3.friend);       "Harry,liam,nail" alert (person4.friend);       "Harry,liam"

This approach combines the advantages of a constructor pattern and a prototype pattern, which defines the instance properties, which are used to define methods and shared properties. Each instance will have its own copy of the instance properties, while also sharing a reference to the method, to maximize memory savings. In this mode person1 changing its Friend property does not affect Person2, because the friend attribute is written in the constructor, and each creation of a new instance generates a new copy of the property. So the friend array in Person1 and Person2 is a different array.

The blending mode of the constructor mode prototype pattern is the most commonly used model for creating objects in the actual development.

Methods for creating custom objects in JavaScript

Related Article

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.