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

Source: Internet
Author: User

Introduction to constructors everyone is familiar, 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 often thought of as implementations of instances, and JavaScript has no class concept, 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", 2010, 5000); 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:functionCar (model, year, miles) { This. Model =model;  This. Year =Year ;  This. Miles =miles;  This. output=Formatcar;}functionFormatcar () {return  This. Model + "Gone" + This. Miles + "km";} This method is available, but we have the following better way. Constructors and prototype 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", 2010, 5000); 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", 2010, 5000); 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://as a function callvarTom = Car ("Uncle", 2009, 20000); Console.log (typeofTom);//"undefined"Console.log (Window.output ());//"20000 km away from the walk."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", 2009, 20000); Console.log (typeofTom);//"Object"Console.log (Tom.output ());//"20000 km away from the walk."forcing the use of new in the example above 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", 2010, 5000); 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 continue executing the code, if you are using the New keyword ( This instanceofCar) is true and will continue to perform the following parameter assignment, if no new is used, ( This instanceofCar) is false and will be returned as a new instance. The original wrapper function JavaScript has 3 of the original wrapper functions: number, String,Boolean, sometimes they are used in two ways://using the original wrapper functionvars =NewString ("My string");varn =NewNumber (101);varb =NewBoolean (true);//recommend thisvars = "My string";varn = 101;varb =trueIt is recommended that you use these wrapper functions only when you want to preserve the numeric state, and you can refer to the following code 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"Summary This chapter mainly explains the use of the constructor mode, the method of invocation and the difference between the new keyword, I hope you have to pay attention to when using. Reference: http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascriptsynchronization and recommendation this article has been synchronized to the directory index: in-depth understanding of JavaScript series in-depth understanding of the JavaScript series, including the original, translation, reprint and other types of articles, if it is useful to you, please recommend supporting a, to the power of the uncle writing. 

In-depth understanding of the JavaScript series (26): Design pattern 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.