Nine ways to create objects in JavaScript

Source: Internet
Author: User
Tags instance method

Introduction to Objects in JavaScript:

ECMA-262 defines an object as: "A collection of unordered attributes whose properties can contain basic values, objects, or functions." "Strictly speaking, this is equivalent to saying that the object is a set of values that do not have a particular order. Each property or method of an object has a name, and each name is mapped to a value. Because of this, we can think of objects in JavaScript as hash lists: nothing more than a set of name-value pairs, where values can be data or functions.


Nine ways to create objects in javascript:

1. Native Object Constructor

2. Object literal notation

3. Factory mode

4. Constructor mode

5. Prototype mode

6. Combination of constructor mode and prototype mode

7. Dynamic prototype mode

8. Parasitic structural function mode

9. Secure Structural function mode

1. Native Object Constructor

Specific examples:
Creating objects
var person = new Object ();
Adding properties to an object
Person.name = "Luochen";
Person.age = 22;
Person.job = "Student";
Add a method to an object
Person.sayjob = function () {
alert (this.job);
};
PS: The above example creates an object named person and adds three properties and a method to it.

2. Object literal notation

Specific examples:
Creating objects
var person = {
Name: "Luochen",
Age:22,
Job: "Student",
Sayjob:function () {
alert (this.job);
}
};
PS: Although an object constructor or object literal can be used to create a single object, there are obvious drawbacks to these approaches: creating multiple objects using the same interface produces a lot of duplicate code.

3 , Factory mode

 specific example: 
//Custom Create object function
function Createperson (name,age,job) {
           var o = new Object ();
           o.name = name;
           o.age = age;
           o.job = job;
           o.sayjob = function () {
                   alert (this.job);          
           };
           return o;
}
var  person1 = Createperson ("Luochen", "student");
PS: The principle of Factory mode is to customize a function that encapsulates the details of creating an object with a specific interface. This function can receive some necessary parameters to initialize the object, inside the function will finally return the new object, outside the function of the call this function to assign the result to a new variable. Factory mode solves the problem of creating multiple similar objects, but does not solve the problem of object recognition.

4. Constructor mode

Specific examples:
Create custom constructors to define properties and methods for custom object types
function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
This.sayjob = function () {
alert (this.job);
};
}
var person1 = new Person ("Luochen", "student");
PS: The difference between a constructor pattern and a factory pattern:
1. Create objects without displaying them
2. Assigning properties and methods directly to the This object
3. No Return statement
Invoking the constructor with the new operator creates an object that actually goes through the following 4 steps:
1. Create a new object
2. Assign the scope of the constructor to the new object (so this will point to the new object)
3. Execute the code in the constructor (add attributes for this new object)
4. Return to new Object
Creating a custom constructor means that its instance can be identified as a specific type in the future, which is where the constructor pattern is better than the factory pattern. The obvious disadvantage of constructors is that each method is recreated on each instance, that is, functions with the same name on different instances are not equal.

5. Prototype mode

Specific examples:
Instead of defining the information for an object instance in the constructor, you can add that information directly to the prototype object
function person () {
}
Person.prototype.name = "Luochen";
Person.prototype.age = 22;
Person.prototype.job = "Student";
Person.prototype.sayJob = function () {
alert (this.job);
};
var person1 = new Person ();
Person1.sayjob ();
PS: Each function we create has a prototype prototype attribute, which is a pointer to an object that is used to contain properties and methods that can be shared by all instances of a particular type, that is, the object that the prototype property points to is the prototype object for all instances. The biggest difference between a prototype pattern and a constructor pattern is that objects created by the prototype schema share all the properties and methods (that is, using the same set of properties and the same function). It is particularly memorable that object instances created through prototype mode do not contain properties and methods, but we can call Person1.sayjob () What is this??? In fact, this is done by looking up the properties of the object. Each time the code reads a property or method of an object, the search is performed once, and the target is a property with the given name. The search begins first from the object instance itself. If a property with the given name is found in the instance, the value of the property is returned, and if it is not found, the prototype object that the pointer (internal property [[Prototype]) of the instance is searched for, and the property with the given name is found in the prototype object. If this property is found in the prototype object, the value of the property is returned.

The more common practice of prototype mode is to rewrite the entire prototype object with an object literal that contains all the properties and methods
function person () {
}
Person.prototype = {
Constructor:person,
Name: "Luochen",
Age:22,
Job: "Student",
Sayjob:function () {
alert (this.job);
}
};
var person1 = new Person ();
PS: The prototype mode omits the link to the constructor pass parameter, results all instances will get the same property value by default, and when there is a property of a reference type value on the prototype object, the result of modifying its value on an object instance will be reflected in all instances.

6. Combination of constructor mode and prototype mode

Specific examples:
Constructor patterns are used to define instance properties, while prototype patterns define methods and shared properties
function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
This.friends = ["Tom", "Jerry"];
}
Person.prototype = {
Constructor:person,
Sayjob:function () {
alert (this.job);
}
};
var person1 = new Person ("Luochen", "student");
var person2 = new Person ("Shelby", "Enginner");

Person1.friends.push ("Van");
alert (person1.friends); "Tom,jerry,van"
alert (person2.friends); "Tom,jerry"
Alert (Person1.friends = = person2.friends); False
Alert (Person1.sayjob = = Person2.sayjob); True
PS: An instance of an object created by combining the constructor pattern and the prototype schema will have its own copy of the instance properties, but at the same time share a reference to the method, saving memory to a minimum. This pattern is one of the most widely used and most recognized methods of creating custom types. Can be said to be used to define a reference type of a default mode.

7. Dynamic prototype mode

Specific examples:
Encapsulates all information in a constructor, determining whether a prototype needs to be initialized by examining the existence of any properties and methods that should exist after the prototype is initialized
function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;

Determine whether to initialize the prototype
if (typeof this.sayjob! = "function") {
Person.prototype.sayJob = function () {
alert (this.job);
};
}
}
var person = new Person ("Luochen", "student");
Person.sayjob ();
PS: For objects created with this pattern, you can also use the instanceof operator to determine its type. When using the dynamic prototype pattern, you cannot rewrite the prototype with object literals, and if you rewrite the prototype with the instance already created, the connection between the existing instance and the new prototype is severed.

8. Parasitic structural function mode

 specific example: 
//The basic idea of this pattern is to create a function that encapsulates the code that creates the object, and then returns the newly created object
function person (name,age,job) {
           var o = new Object ();
           o.name = name;
           o.age = age;
           o.job = job;
           o.sayjob = function () {
                   alert (this.job);
           };
           return o;
}
var person = new Person ("Luochen", "student");
Person.sayjob ();
PS: This mode is exactly the same as the Factory mode, except that the new operator is used and the wrapper function is called a constructor function. The constructor returns a new object instance by default, without returning a value. Instead, you can override the value returned when the constructor is called by adding a return statement at the end of the constructor. The disadvantage of this pattern is that the type of the object cannot be determined by the instanceof operator because the returned object is not related to the constructor or to the stereotype property of the constructor.

9. Secure Structural function mode

Specific examples:
The secure constructor follows a pattern similar to the parasitic constructor, but has a difference of two points: first, the instance method of the newly created object does not reference this, and the constructor is not called with the new operator
function Person (name,age,job) {
var o = new Object ();
O.name = name;
O.age = age;
O.job = job;
O.sayjob = function () {
alert (name);
};
return o;
}
var person = person ("Luochen", "student");
Person.sayjob ();
PS: The variable person holds a secure object (that is, there is no public property, and its methods do not refer to this object), and there is no other way to access its data members than to call the Sayjob () method. Similar to the parasitic constructor pattern, objects created with the secure constructor pattern have no relation to the constructor, so the instanceof operator does not make sense for this object.






This article from "Luo Chen's Blog" blog, reproduced please contact the author!

Nine ways to create objects in JavaScript

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.