In-depth understanding of the JavaScript series (26): Design pattern constructor mode

Source: Internet
Author: User

Introduced

Constructors are familiar to everyone, but if you are a novice, it is necessary to understand what is called a constructor. Constructors are used to create objects of a particular type-not only the objects that are used, but also parameters that the constructor can accept to set the object's member values the first time the object is created. You can customize your own constructor, and then declare the properties or methods of the custom type object inside.

Basic usage

In JavaScript, constructors are generally thought to be used to implement instances, and JavaScript has no concept of class, but there are special constructors. Using the new keyword to invoke the defined no-early function, you can tell JavaScript that you want to create a new object and that the member declaration of the new object is defined in the constructor. Inside the constructor, the This keyword refers to the newly created object. The basic usage is as follows:

functionCar (model, year, miles) { This. model = model; This. year = year; This. Miles = Miles; This. output=function() {return  This. Model + "Gone" + This. Miles + "km"; };}varTom=NewCar ("Uncle", 2009, 20000);vardudu=NewCar ("Dudu"), Console.log (Tom.output ()); Console.log (Dudu.output ());

The above example is a very simple constructor pattern, but a little bit of a problem. First, it is cumbersome to use inheritance, and then output () is redefined every time the object is created, the best way is to have all instances of car type share this output () method, so that if there is a large number of instances, it will save a lot of memory.

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

function  Car (model, year, miles) {this . Model =    Model    this . Year = year;    this . Miles = Miles; this . output= Formatcar;} function  Formatcar () {return  this . Model + "Gone" + this . Miles + "km";} 

This method is available, but we have the following better way.

Constructors and prototypes

JavaScript functions have a prototype property called prototype, and when the constructor is called to create the object, all properties of the constructor prototype are available on the newly created object. In this way, multiple car object instances can share the same prototype, and we'll extend the code for the previous example:

functionCar (model, year, miles) { This. model = model; This. year = year; This. Miles = Miles;}/*Note: Here we use the Object.prototype. Method name instead of Object.prototype is primarily used to avoid overriding the definition of a prototype prototype object*/car.prototype.output=function() {return  This. Model + "Gone" + This. Miles + "km";};varTom =NewCar ("Uncle", 2009, 20000);varDudu =NewCar ("Dudu"), Console.log (Tom.output ()); Console.log (Dudu.output ());

Here, an output () Single instance can be shared with all car object instances.

In addition: We recommend that constructors start with uppercase letters in order to differentiate between normal functions.

Can I use new?

The example above is for the function car to use new to create the object, only this way? In fact there are other ways, we list two kinds:

functionCar (model, year, miles) { This. model = model; This. year = year; This. Miles = Miles;//customizing one output content     This. Output =function() {return  This. Model + "Gone" + This. Miles + "km"; }}//Method 1: Call as a functionCar ("Uncle", 2009, 20000);//Add to Window objectConsole.log (Window.output ());//Method 2: Call within the scope of another objectvaro =NewObject (); Car.call (O, "Dudu", ","), Console.log (O.output ());

The code of Method 1 is a bit special, if you do not apply the new direct call function, this point is the Global Object window, let us verify:

//    Span style= "Color:rgb (0,0,255); Line-height:1.5!important ">var  tom = Car (" Uncle "," 20000 "), Console.log (typeof  Tom); // " undefined "   Console.log (Window.output ()); // " The uncle walked 20000 kilometers.  

This time the object Tom is undefined, and window.output () will correctly output the results, and if the use of the New keyword does not have this problem, verify the following:

//Use the New keywordvarTom =NewCar ("Uncle", 20000); Console.log (typeofTom);//"Object"Console.log (Tom.output ());//"20000 km away from the walk."
Force the use of new

The above example shows the question of not using new, so do we have a way to force the constructor to use the New keyword, the answer is yes, on the code:

functionCar (model, year, miles) {if(! ( This instanceofCar)) {return NewCar (model, year, miles); } This. model = model; This. year = year; This. Miles = Miles; This. Output =function() {return  This. Model + "Gone" + This. Miles + "km"; }}varTom =NewCar ("Uncle", 2009, 20000);varDudu = Car ("Dudu", ",") Console.log (typeofTom);//"Object"Console.log (Tom.output ());//"20000 km away from the walk."Console.log (typeofDudu);//"Object"Console.log (Dudu.output ());//"Dudu 5000 km away."

By judging if the instanceof of this is car to decide whether to return to new car or to continue executing the code, if the new keyword is used, then (this instanceof Car) is true, the following parameter assignment will continue to be performed. If you do not use new,(this instanceof Car) is false, it will be re-returned to the new instance.

Original wrapper function

There are 3 original wrapper functions in javascript: Number, String, Boolean, and sometimes both:

//using the original wrapper functionvars =NewString ("my string");varn =NewNumber (101);varb =NewBoolean (true);//recommend thisvars = "my string";varn = 101;varb =true;

It is recommended that you use these wrapper functions only when you want to preserve the numeric state, and the following code is useful for the difference:

//Original Stringvargreet = "Hello there";//split using the Split () methodGreet.split (") [0];//"Hello"//adding a new property to the original type does not give an errorGreet.smile =true;//This value cannot be obtained (chapter 18 ECMAScript The implementation of why we Speak)Console.log (typeofGreet.smile);//"undefined"
//Original StringvarGreet =NewString ("Hello there");//split using the Split () methodGreet.split (") [0];//"Hello"//adding a new property to the wrapper function type does not give an errorGreet.smile =true;//new properties can be accessed normallyConsole.log (typeofGreet.smile);//"Boolean"
Summarize

This chapter mainly explains the use of the constructor mode, the method of invocation and the difference between the new keyword, I hope everyone in the use of attention.

Copyright NOTICE: This article for Bo Master http://www.zuiniusn.com original article, without Bo Master permission not reproduced.

In-depth understanding of the JavaScript series (26): Design pattern constructor mode

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.