Learning JavaScript Design Patterns the Constructor Pattern

Source: Internet
Author: User

In classical object-oriented programming languages, a constructor are a special method used to initialize a newly created O Bject once memory has a been allocated for it. In JavaScript, as almost everything are an object, we ' re most often interested in object constructors.

Object constructors is used to create specific types of Objects-both preparing the object for use and accepting argumen TS which a constructor can use-set the values of member properties and methods when the object is first created.

Object Creation

The three common ways to create new objects in JavaScript is as follows:

// Each of the following options would create a new empty object: var newObject =//  orvar newObject =//  or var New Object ();

Where the "Object" constructor in the final example creates an Object wrapper for a specific value, or where no value is P assed, it'll create an empty object and return it.

There is then four ways in which keys and values can then is assigned to an object:

//ECMAScript 3 compatible approaches //1. Dot Syntax //Set PropertiesNewobject.somekey = "Hello World"; //Get PropertiesvarValue =Newobject.somekey;  Console.log (value); //2. Square Bracket Syntax //Set Propertiesnewobject["Somekey"] = "Hello World"; //Get PropertiesvarValue = newobject["Somekey"]; Console.log (value); //ECMAScript 5 only compatible approaches//For more information see:http://kangax.github.com/es5-compat-table/ //3. Object.defineproperty //Set PropertiesObject.defineproperty (NewObject, "Somekey", {value:"For more control on the property ' s behavior", writable:true, Enumerable:true, Configurable:true}); //If The above feels a little difficult to read, a short-hand could//Be written as follows: varDefineprop =function(obj, key, value) {varConfig ={value:value, writable:true, Enumerable:true, Configurable:true  }; Object.defineproperty (obj, key, config);}; //to use, we then create a new empty ' person ' objectvarperson =object.create (object.prototype);//Populate the object with propertiesDefineprop (person, "car", "DeLorean");d Efineprop (person,"dateOfBirth", "1981");d Efineprop (person,"Hasbeard",false ); Console.log (person);//outputs:object {car: "DeLorean", dateOfBirth: "1981", Hasbeard:false}  //4. Object.defineproperties //Set Propertiesobject.defineproperties (newObject, {"Somekey": {value:"Hello World", writable:true  },   "Anotherkey": {value:"Foo Bar", writable:false  } }); //Getting Properties for 3. and 4. Can is done using any of the//options in 1. and 2.</script> </body>

As we'll see a little later in the book, these methods can even is used for inheritance, as follows:

// Usage: // Create a race car driver that inherits from the person object var driver =//  Set Some propertiesfor the driver Defineprop (driver, "topSpeed", " 100mph "//  Get an inherited property (1981)//  Get the property We set (100mph)console.log (driver.topspeed);
Basic Constructors

As we saw earlier, JavaScript doesn ' t support the concept of classes but it does support special constructor functions tha t work with objects. By simply prefixing a call to a constructor function with the keyword ' new ', we can tell JavaScript we would like the Func tion to behave as a constructor and instantiate a new object with the members defined by.

Inside a constructor, the keyword this references the new object that's being created. Revisiting object creation, a basic constructor may look as follows:

functionCar (model, year, miles) { This. Model =model;  This. Year =Year ;  This. Miles =miles;  This. toString =function () {    return  This. Model + "have done" + This. Miles + "Miles"; };} //Usage: //We can create new instances of the carvarCIVIC =NewCar ("Honda Civic", 2009, 20000 );varMondeo =NewCar ("Ford Mondeo", 2010, 5000 ); //And then open we browser console to view the//output of the toString () method being called on//these objectsConsole.log (civic.tostring ()); Console.log (mondeo.tostring ());

The above is a simple version of the constructor pattern but it does suffer from some problems. One is, it makes inheritance difficult and the other was that functions such as was redefined for each of the toString() new Objects created using the Car constructor. This isn ' t very optimal as the function should ideally is shared between all of the instances of the Car type.

Thankfully as there is a number of both ES3 and es5-compatible alternatives to constructing objects, it's trivial to work Around this limitation.

Constructors with prototypes

Functions, like almost all objects in JavaScript, contain a "prototype" object. When we call a JavaScript constructor to create an object, all the properties of the constructor ' s prototype is then made Available to the new object. In this fashion, multiple Car objects can be created which access the same prototype. We can thus extend the original example as follows:

functionCar (model, year, miles) { This. Model =model;  This. Year =Year ;  This. Miles =miles;} //Note Here, we are using Object.prototype.newMethod rather than//Object.prototype so as to avoid redefining the prototype ObjectCar.prototype.toString =function () {  return  This. Model + "have done" + This. Miles + "Miles";}; //Usage: varCIVIC =NewCar ("Honda Civic", 2009, 20000 );varMondeo =NewCar ("Ford Mondeo", 2010, 5000 ); Console.log (Civic.tostring ()); Console.log (mondeo.tostring ());

Above, a single instance of ToString () 'll now is shared between all of the Car objects.

Learning JavaScript Design Patterns the Constructor Pattern

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.