Methods of creating objects based on JavaScript

Source: Internet
Author: User

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 the ECMAScript object as a hash table: nothing more than a set of name-value pairs, where values can be data or functions.


There are various ways to create objects, and it is important to understand and master each method of creating objects for the language of JavaScript.

First, use the object constructor

var person = new Object ();//note here the first letter of object must be capitalized person.name = "Zhangsan";p erson.age = 21;person.sex = "Male"; Person.sayname = function () {alert (this.name);}

The example above creates an object named person and adds three attributes (Name,age,sex) and a Method (Sayname ()) to it.


Ii. creating objects using literals

var person = {Name: "Zhangsan", age:21, Sex: "Male", Sayname:function () {alert (this.name); }}

Creating objects using literals is similar to creating objects using the object constructor above, like enrolling at the beginning of the semester, every student who has to write a name, age, gender of the words, obviously efficiency what low, because this method will produce a lot of duplicate code. To solve this problem, people started to create objects using Factory mode.


Third, the factory model

Factory mode, as the name implies, is like a factory, the objects from the assembly line have the same properties and methods. Considering the inability to create a class in ECMAScript, the developer invented a function that encapsulates the details of creating an object with a specific interface, as in the following example:

function Createperson (name,age,sex) {var obj = new Object ();    Obj.name = name;    Obj.age = age;    Obj.sex = sex;    Obj.sayname = function () {alert (this.name); } return obj; var person1 = Createperson ("Zhangsan", "male"), var person2 = Createperson ("Lisi", "female");

Factory mode seems to solve the problem of creating multiple similar objects, but it does not solve the problem of object recognition, that is, how to know the type of an object. With the development of JavaScript, there is a new pattern to emerge.


Four, the structure function pattern

We know that native constructors like object and array will automatically appear in the execution environment at run time, and we can also create custom constructors to define properties and methods for custom object types. Give me a chestnut as follows:

function Person (name,age,sex) {this.name = name;    This.age = age;    This.sex = sex;    This.sayname = function () {alert (this.name); }}var Person1 = new Person ("Zhangsan", "n", "male"), var person2 = new Person ("Lisi", "female");

In this example, the person function replaces the Createperson () function above. We note that the code in person () has the following differences in addition to the same parts in Createperson ():

1. Create objects without displaying them

2. Assign properties and methods directly to the This object

3. No Return statement

It should also be noted that the function is named person using the first letter capital P. As a rule, constructors should always start with an uppercase letter, while non-constructors should start with a lowercase letter.

To create a new instance of person, you must use the new operator. Calling a constructor in this way actually goes through the following four steps:

1. Create a new object

2. Assign the scope of the constructor to the new object (so this points to the new object);

3. Execute the code in the constructor (add attributes for this new object)

4. Return to new Object


V. Prototype model


Each function that we create has a prototype (prototype) attribute, which is a pointer to an object, and the purpose of this object is to include properties and methods that can be shared by all instances of a particular type.

function person () {}person.prototype.name = "Zhangsan"; Person.prototype.age = 19; Person.prototype.sex = "male"; Person.prototype.sayName = function () {alert (this.name);}; var person1 = new Person (), var person2 = new Person ();p erson1.name = "Lisi"; alert (person1.name);//"Lisi"-from the example alert ( Person2.name);//"Zhangsan"-from the prototype delete Person1.name;alert (person1.name);//"Zhangsan"--from the prototype

Prototyping mode is also not without drawbacks. First, it omits the process of passing initialization parameters to the constructor, resulting in all instances getting the same property value by default. Although this will somehow bring some inconvenience, but not the biggest problem of the prototype, the biggest problem of the prototype model is caused by its shared nature. Here is an example to illustrate:

function Person (name,age,sex) {}person.prototype = {Constructor:person, name: "Zhangsan", age:19, Sex: "Ma    Le ", Friends: [" Bob "," Jams "], Sayname:function () {alert (this.name); }}var Person1 = new Person (), var person2 = new Person ();p Erson1.friends.push ("Obama"), alert (person1.friends),//bob, Jams,obamaalert (person2.friends);//bob,jams,obamaalert (person1.friends = = = Person2.friends);//true


Vi. combining the constructor pattern with the prototype pattern


  The most common way to create custom types is by combining the constructor pattern with the prototype pattern. The constructor pattern is used to define instance properties, and the prototype schema is used to define methods and shared properties. As a result, each instance will have its own copy of the instance properties, but at the same time it shares a reference to the method, saving the memory to a minimum. In addition, this blending mode supports passing parameters to the constructor, which is the length of the set of two modes.

function person (name,age,sex) {    this.name  = name;    this.age = age;    this.sex = sex;     this.friends = ["Bob", "Jams"];} person.prototype = {    constructor : person,     Sayname: function () {        alert (this.name);     }}var person1 = new person ("Zhangsan", "male"); var person2 = new  person ("Lisi", "female");p Erson1.friends.push ("Obama"), alert (person1.friends);//bob,jams,obamaalert ( Person2.friends);//bob,jamsalert (person1.friends === person2.friends);//falsealert (person1.sayName  === person2.sayname);//true 

In this example, the instance properties are defined in the constructor, and the properties constructor and Method Sayname () shared by all instances are defined in the prototype. Modifying the person1.friends does not affect the person2.friends as it did in the previous example.


Seven, dynamic prototype mode

the benefit of this pattern is that it looks more like traditional object-oriented programming, and has better encapsulation because it completes the prototype creation in the constructor.

function Person (name,age,sex) {this.name = name;    This.age = age;    This.sex = sex;        if (typeof this.sayname! = "function") {Person.prototype.sayName = function () {alert (this.name); }}}var person = new Person ("Zhangsan", "male");p erson.sayname ();

In addition to the above methods, there are parasitic constructor patterns and safe constructor modes. In fact, in so many ways, the sixth and seventh are the most commonly used, we need to use different methods according to the actual situation, to be able to improvise more efficient work.

This article is from the "Fcheng" blog, make sure to keep this source http://fcheng.blog.51cto.com/10644114/1839597

Methods of creating objects based on 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.