JavaScript Creation object (Factory mode and constructor mode)

Source: Internet
Author: User
Tags uppercase letter

Although the object constructor or object literal can create a single object, there are obvious drawbacks to these approaches: creating many objects with the same interface produces a lot of duplicated code. To solve this problem, you can use Factory mode to create objects.

1. Factory mode
In ECMAScript, where classes cannot be created, developers invent a function that encapsulates the details of a particular interface's creation object.

 function createperson(name, age, Job) {    varo =New Object();    O.name = name;    O.age = age;    O.job = job; Sayname = function () {Alert This. name); };returno;}varPerson1 = Createperson (' Zxj ', at,"Software Engineer");varPerson2 = Createperson (' SDF ', -,"Software Engineer");

As we can see in the example, the factory pattern solves the problem of creating multiple similar objects, but does not solve the problem of object recognition (in the example, the O object is the object's type).

2. Constructor mode
We know that constructors in ECMAScript can be used to create objects of a particular type. Native constructors like object and array are automatically present in the execution environment at run time. In addition, you can create custom constructors that define properties and methods for custom object types. The code looks like this:

 function createperson(name, age, Job) {     This. name = name; This. Age = Age; This. Job = job; Sayname = function () {Alert This. name); };}varPerson1 =NewPerson (' Zxj ', at,"Software Engineer");varPerson2 =NewPerson (' SDF ', -,"Software Engineer");

In this example, the person () function replaces the Createperson () function. We note that the code in person () has the following differences in addition to the same parts as Createperson ():
There is no explicit creation of an object;
The properties and methods are assigned directly to the This object;
no return statement;
In addition, the function name person uses the capital letter p. By convention, constructors should always start with an uppercase letter, and not a constructor should start with a lowercase letter. The main purpose is to distinguish it from other functions in Ecmascrit, because the constructor itself is also a function, but it can be used to create objects.
To create a new force for the person object, you must use new operator. Calling a constructor in this way actually goes through the following 4 steps:
Create a new object;
Assigns the scope of the constructor to the new object (so this will point to the new object);
Executes the code in the constructor (adding properties and methods to the new object);
Returns the new object;
Therefore, Person1 and person2 each hold a different instance of person. Both objects have a constructor (constructor) property that points to person as follows:

alert(person1.constructor//truealert(person2.constructor//true

For the Contructor property, it was originally used to identify the object type. However, it is more reliable to refer to the detection object type, or the instanceof operator, as follows:

instanceofObject//trueinstanceof//trueinstanceofObject//trueinstanceof//true

Creating a custom constructor means that its instance can be identified in the future as a specific type, which is where the constructor pattern trumps the factory pattern. In this example, Peron1 and Person2 are both instances of object because all objects inherit from object.
Use constructors as functions
The only difference between a constructor and a normal function is that they are called in different ways. Any function, as long as it is called by the new operator, is a constructor, which is a normal function if it is not called by the new operator. As shown below:

//As a constructorvarperson =NewPerson (' Zxj ', at,"Software Engineer");p Erson.sayname ();//ZXJ//As a normal functionPerson (' SDF ', -,"Software Engineer");//Add to WindowWindow.sayname ();//saf//called in the scope of another objectvarn \New Object(); Person.call (O,"Qwe", -,"Nurse"); O.sayname ();//qwe

Problems with constructors
The disadvantage of constructors is that each method is recreated over each instance. In the preceding example, both Person1 and Person2 have a method named Sayname, but the two methods do not belong to the same object.

alert(person1.sayName == person.sayName())// false

So can we share a sayname () method. If you want to do this, you can move the function definition to the outside of the constructor, just like the code below.

 function person(name, age, Job) {     This. name = name; This. Age = Age; This. Job = job; This. Sayname = Sayname;} function sayname() {Alert This. name);};varPerson1 =NewPerson (' Zxj ', at,"Software Engineer");varPerson2 =NewPerson (' SDF ', -,"Software Engineer");

When two instances require a public property or method, they need to be defined outside the constructor and then referenced inside the constructor.
The practice in the above example does solve the problem of two functions doing the same thing, but again: the function defined in the global scope is actually only called by an object, which makes the global scope a bit of a misnomer. However, when these public methods are many, we need to define multiple global functions, so we have no encapsulation of this custom reference type.
Fortunately, these problems can be solved through the prototype model, JS prototype inheritance has said.

JavaScript Creation object (Factory mode and constructor mode)

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.