Deep understanding of the JavaScript series (26): Design patterns in the form of structural function patterns _javascript skills

Source: Internet
Author: User
Tags wrapper

Introduced

Constructors are familiar, but if you're a novice, it's important to know what a constructor is. Constructors are used to create objects of a particular type--not only are the objects used, but also the constructors can accept parameters 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, a constructor is usually considered to implement an instance, and JavaScript has no concept of a class, but has a special constructor. Call the defined early function by using the new keyword, and you can tell JavaScript that you want to create a new object and that the new object's member declarations are defined in the constructor. Inside the constructor, the This keyword refers to the newly created object. The basic usage is as follows:

Copy Code code as follows:

function car (model, year, miles) {
This.model = model;
This.year = year;
This.miles = miles;
this.output= function () {
return This.model + "Gone" + This.miles + "km";
};
}

var tom= new car ("Uncle", 2009, 20000);
var dudu= new car ("Dudu", 2010, 5000);

Console.log (Tom.output ());
Console.log (Dudu.output ());

The example above is a very simple constructor pattern, but there is a slight problem. The first is that using inheritance is cumbersome, and then output () is redefined each time the object is created, and the best approach is to have all instances of the car type share the output () method, which saves a lot of memory if there are large quantities of instances.

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

Copy Code code as follows:

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";
}


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

Constructors and prototypes

JavaScript functions have a prototype property called prototype, and when the constructor is invoked, all the properties of the constructor prototype are available on the newly created object. By doing so, multiple car object instances can share the same prototype, and we extend the code for the example above:

Copy Code code as follows:

function car (model, year, miles) {
This.model = model;
This.year = year;
This.miles = miles;
}

/*
Note: Here we use the Object.prototype. Method name, not Object.prototype
Primarily used to avoid overriding the definition of a prototype prototype object
*/
car.prototype.output= function () {
return This.model + "Gone" + This.miles + "km";
};

var tom = new Car ("Uncle", 2009, 20000);
var Dudu = new Car ("Dudu", 2010, 5000);

Console.log (Tom.output ());
Console.log (Dudu.output ());


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

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

Can I use new?

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

Copy Code code as follows:

function car (model, year, miles) {
This.model = model;
This.year = year;
This.miles = miles;
Customizing an output content
This.output = function () {
return This.model + "Gone" + This.miles + "km";
}
}

Method 1: Called as a function
Car ("Uncle", 2009, 20000); Add To Window object
Console.log (Window.output ());

Method 2: Calling in the scope of another object
var o = new Object ();
Car.call (O, "Dudu", 2010, 5000);
Console.log (O.output ());


The code's Method 1 is a bit special, if the new direct call function is not applicable, this point is the Global Object window, let's verify:
Copy Code code as follows:

As a function call
var tom = car ("Uncle", 2009, 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 output the result correctly, and if you use the New keyword there is no problem, verify as follows:
Copy Code code as follows:

Use the New keyword
var tom = new Car ("Uncle", 2009, 20000);
Console.log (typeof Tom); "Object"
Console.log (Tom.output ()); "The uncle walked 20000 kilometers."

Enforce use of new

The above example shows the problem 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:

Copy Code code as follows:

function car (model, year, miles) {
if (!) ( This instanceof car) {
Return to new car (model, year, miles);
}
This.model = model;
This.year = year;
This.miles = miles;
This.output = function () {
return This.model + "Gone" + This.miles + "km";
}
}

var tom = new Car ("Uncle", 2009, 20000);
var Dudu = car ("Dudu", 2010, 5000);

Console.log (typeof Tom); "Object"
Console.log (Tom.output ()); "The uncle walked 20000 kilometers."
Console.log (typeof Dudu); "Object"
Console.log (Dudu.output ()); "Dudu walked 5000 miles."


By deciding whether the instanceof of this is the car to return to new car or continue executing the code, if the new keyword is used, (this instanceof car) is true, the following parameter assignment will continue, if not new, (this instanceof car) is a fake and will be returned with a new instance.

Original wrapper function

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

Copy Code code as follows:

Using the original wrapper function
var s = new String ("My String");
var n = new number (101);
var B = new Boolean (true);


Recommend this
var s = "My string";
var n = 101;
var B = true;


It is recommended that you use these wrapper functions only when you want to preserve numeric status, and refer to the following code for the difference:
Copy Code code as follows:

Raw string
var greet = "Hello there";
Using the Split () method to split
Greet.split (") [0]; "Hello"
Adding new attributes to the original type does not give an error
Greet.smile = true;
It's impossible to get this value (18 chapter ECMAScript Implementation we're talking about why)
Console.log (typeof Greet.smile); "Undefined"

Raw string
var greet = new String ("Hello there");
Using the Split () method to split
Greet.split (") [0]; "Hello"
Adding a new property to a wrapper function type does not give an error
Greet.smile = true;
New properties can be accessed normally
Console.log (typeof Greet.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.

Reference: http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/

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.