In-depth understanding of the JavaScript series (26): Detailed description of the constructor mode in the Design Mode

Source: Internet
Author: User

In-depth understanding of the JavaScript series (26): Detailed description of the constructor mode in the Design Mode

This article mainly introduces a deep understanding of the JavaScript series (26): Detailed description of the constructor mode of the design pattern. This article explains the basic usage, constructor and prototype, and can only use new? Mandatory use of new, original packaging functions, and other content. For more information, see

 

 

Introduction

Constructors are familiar to everyone, but if you are a newbie, you still need to know what constructor is. The constructor is used to create a specific type of object-not only declares the used object, but also accepts parameters for the constructor to set the object member value when the object is created for the first time. You can customize your own constructor and declare the attributes or methods of the custom type object in it.

Basic usage

In JavaScript, constructor is generally considered to be used to implement instances. JavaScript does not have the concept of classes, but has special constructor. The new keyword is used to call the defined functions. You can tell JavaScript that you want to create a new object and the member declarations of the new object are defined in the constructor. Within the constructor, The this keyword references the newly created object. The basic usage is as follows:

The Code is as follows:


Function Car (model, year, miles ){
This. model = model;
This. year = year;
This. miles = miles;
This. output = function (){
Return this. model + "go" + this. miles + "km ";
};
}

 

Var tom = new Car ("uncle", 2009,200 00 );
Var dudu = new Car ("Dudu", 2010,500 0 );

Console. log (tom. output ());
Console. log (dudu. output ());

 

The above example is a very simple constructor mode, but it is a little problematic. First, it is very troublesome to use inheritance. Secondly, output () is redefined every time an object is created. The best way is to share this output () with all Car-type instances () in this way, if there are a large number of instances, it will save a lot of memory.

To solve this problem, we can use the following method:

The Code is as follows:


Function Car (model, year, miles ){
This. model = model;
This. year = year;
This. miles = miles;
This. output = formatCar;
}

 

Function formatCar (){
Return this. model + "go" + this. miles + "km ";
}


Although this method is available, we have the following better methods.

 

Constructor and prototype

In JavaScript, a function has a prototype attribute. When a constructor is called to create an object, all attributes of the constructor prototype are available on the newly created object. In this way, multiple Car object instances can share the same prototype. let's expand the code of the previous example:

The Code is as follows:


Function Car (model, year, miles ){
This. model = model;
This. year = year;
This. miles = miles;
}

 

/*
Note: The Object. prototype. method name is used here, instead of Object. prototype.
It is mainly used to avoid rewriting the prototype object of the definition prototype.
*/
Car. prototype. output = function (){
Return this. model + "go" + this. miles + "km ";
};

Var tom = new Car ("uncle", 2009,200 00 );
Var dudu = new Car ("Dudu", 2010,500 0 );

Console. log (tom. output ());
Console. log (dudu. output ());


Here, an output () instance can be shared among all Car object instances.

 

In addition, we recommend that constructors start with an uppercase letter to distinguish common functions.

Can only use new?

In the above example, the car function uses new to create objects. Is this the only method available? There are other methods as follows:

The Code is as follows:


Function Car (model, year, miles ){
This. model = model;
This. year = year;
This. miles = miles;
// Customize an output content
This. output = function (){
Return this. model + "go" + this. miles + "km ";
}
}

 

// Method 1: called as a function
Car ("uncle", 2009,200 00); // Add to the window object
Console. log (window. output ());

// Method 2: Call within the scope of another object
Var o = new Object ();
Car. call (o, "Dudu", 2010,500 0 );
Console. log (o. output ());


Method 1 of the Code is a bit special. If new does not apply to calling a function directly, this points to the Global Object window. Let's verify it:

The Code is as follows:


// Called as a function
Var tom = Car ("uncle", 2009,200 00 );
Console. log (typeof tom); // "undefined"
Console. log (window. output (); // "Uncle walked 20000 kilometers"


At this time, the object tom is undefined, and window. output () will output the result correctly. If the new keyword is used, the problem is not found. The verification is as follows:

The Code is as follows:


// Use the new Keyword
Var tom = new Car ("uncle", 2009,200 00 );
Console. log (typeof tom); // "object"
Console. log (tom. output (); // "Uncle walked 20000 kilometers"

 

Force use new

The above example shows the question of not using new. Is there any way for the constructor to force the use of the new keyword? The answer is yes. The Code is as follows:

The Code is as follows:


Function Car (model, year, miles ){
If (! (This instanceof Car )){
Return new Car (model, year, miles );
}
This. model = model;
This. year = year;
This. miles = miles;
This. output = function (){
Return this. model + "go" + this. miles + "km ";
}
}

 

Var tom = new Car ("uncle", 2009,200 00 );
Var dudu = Car ("Dudu", 2010,500 0 );

Console. log (typeof tom); // "object"
Console. log (tom. output (); // "Uncle walked 20000 kilometers"
Console. log (typeof dudu); // "object"
Console. log (dudu. output (); // "Dudu 5000"


Determine whether to return the new Car or continue executing the code by judging whether the instanceof this is Car. If the new keyword is used, the (this instanceof Car) is true and the following parameter assignment will continue, if new is not used, (this instanceof Car) is false, and a new instance is returned.

 

Original packaging function

In JavaScript, there are 3 original packaging functions: number, string, boolean, and sometimes both use:

The Code is as follows:


// Use the original packaging function
Var s = new String ("my string ");
Var n = newnumber (101 );
Var B = new Boolean (true );

 


// Recommended
Var s = "my string ";
Var n = 101;
Var B = true;


We recommend that you use these packaging functions only when you want to retain the value status. For the difference, refer to the following code:

The Code is as follows:


// Original string
Var greet = "Hello there ";
// Use the split () method for segmentation
Greet. split ('') [0]; //" Hello"
// No error will be reported if you add new attributes to the original type.
Greet. smile = true;
// This value cannot be obtained for a single order (we have explained why in Chapter 18 ECMAScript implementation)
Console. log (typeof greet. smile); // "undefined"

 

// Original string
Var greet = new String ("Hello there ");
// Use the split () method for segmentation
Greet. split ('') [0]; //" Hello"
// No error will be returned when a new property is added to the wrapped function type.
Greet. smile = true;
// You can access the new property normally.
Console. log (typeof greet. smile); // "boolean"

 

Summary

This chapter mainly explains the differences between the usage method, call method, and new Keyword of the constructor mode. I hope you will pay attention to it when using it.

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.