Deep understanding of JavaScript object creation patterns

Source: Internet
Author: User
Tags closure constant constructor hasownproperty

Introduced
This article is mainly about creating objects in the next chapter of the pattern, using a variety of techniques can greatly avoid errors or can write very concise code.

Mode 6: Functional grammar sugar
function syntax sugar is an extension of the method (function) that is quickly added to an object, this is mainly the use of prototype features, the code is relatively simple, we first look at the implementation code:

The code is as follows Copy Code
if (typeof Function.prototype.method!== "Function") {
Function.prototype.method = function (name, implementation) {
This.prototype[name] = implementation;
return this;
};
}

When you extend an object, you can use this:

The code is as follows Copy Code
var person = function (name) {
THIS.name = name;
}
. Method (' GetName ',
function () {
return this.name;
})
. Method (' SetName ', function (name) {
THIS.name = name;
return this;
});

This adds the 2 methods of GetName and setname to the person function, and then we'll verify the results:

The code is as follows Copy Code
var a = new person (' Adam ');
Console.log (A.getname ()); ' Adam '
Console.log (A.setname (' Eve '). GetName ()); ' Eve '

Pattern 7: Object Constants
Object constants are the embodiment of various methods of providing set,get,ifdefined in an object, and the set method preserves only the object that was set first, and the later settings are invalid, and have reached the goal that others cannot overload. The implementation code is as follows:

The code is as follows Copy Code

var constant = (function () {
var constants = {},
Ownprop = Object.prototype.hasOwnProperty,
Only allow these three types of values to be set
allowed = {
String:1,
Number:1,
Boolean:1
},
prefix = (math.random () + "_"). Slice (2);

return {
Set a property with name named
Set:function (name, value) {
if (this.isdefined (name)) {
return false;
}
if (!ownprop.call (Allowed, typeof value)) {
return false;
}
Constants[prefix + Name] = value;
return true;
},
To determine if there is a property named name
Isdefined:function (name) {
Return Ownprop.call (constants, prefix + name);
},
Get a property with name named
Get:function (name) {
if (this.isdefined (name)) {
return constants[prefix + name];
}
return null;
}
};
} ());

The validation code is as follows:

The code is as follows Copy Code

Check to see if there is
Console.log (constant.isdefined ("MaxWidth")); False

Defined
Console.log (Constant.set ("MaxWidth", 480)); True

Re-detect
Console.log (constant.isdefined ("MaxWidth")); True

Try Redefining
Console.log (Constant.set ("MaxWidth", 320)); False

Determine if the original definition still exists
Console.log (Constant.get ("MaxWidth")); 480

Mode 8: Sandbox mode
The sandbox (Sandbox) mode provides a separate context for one or more modules at once, without affecting the context of other modules, for example, there are 3 methods Event,dom,ajax in a Sandbox, in which 2 are called to form an environment. and call three components of the environment completely without interference. The sandbox implementation code is as follows:

The code is as follows Copy Code

function Sandbox () {
To convert an argument to an array
var args = Array.prototype.slice.call (arguments),
The last parameter is callback
callback = Args.pop (),
Except for the last parameter, the other is the module to select
Modules = (Args[0] && typeof args[0] = = = "string")? Args:args[0],
I

Force use of the new operator
if (!) ( This instanceof Sandbox)) {
return new Sandbox (modules, callback);
}

Add properties
THIS.A = 1;
this.b = 2;

You want to add a module to the This object
If there is no module or the incoming parameter is "*", it is assumed that all modules are passed in
if (!modules | | modules = = ' * ') {
modules = [];
For (i in Sandbox.modules) {
if (Sandbox.modules.hasOwnProperty (i)) {
Modules.push (i);
}
}
}

Initialize the required modules
for (i = 0; i < modules.length i + + 1) {
Sandbox.modules[modules[i]] (this);
}

Call callback
Callback (this);
}

To add a prototype object by default
Sandbox.prototype = {
Name: "My Application",
Version: "1.0",
Getname:function () {
return this.name;
}
};

Then we define the default initial module:

The code is as follows Copy Code

Sandbox.modules = {};

Sandbox.modules.dom = function (box) {
Box.getelement = function () {
};
Box.getstyle = function () {
};
Box.foo = "Bar";
};

Sandbox.modules.event = function (box) {
Access to the Sandbox prototype if needed:
BOX.CONSTRUCTOR.PROTOTYPE.M = "MMM";
Box.attachevent = function () {
};
Box.detachevent = function () {
};
};

Sandbox.modules.ajax = function (box) {
Box.makerequest = function () {
};
Box.getresponse = function () {
};
};

The method is invoked as follows:

The code is as follows Copy Code

Call mode
Sandbox ([' Ajax ', ' event '], function (box) {
Console.log (typeof (Box.foo));
Dom is not selected, so Box.foo does not exist
});

Sandbox (' Ajax ', ' Dom ', function (box) {
Console.log (typeof (Box.attachevent));
No event is selected, so the attachevent defined in the event does not exist.
});

Sandbox (' * ', function (box) {
Console.log (box); All of the methods defined above are accessible
});

Through three different invocation modes, we can see that the context environment of the three ways is different, and the first kind has no Foo; The second type has no attachevent, because only the Ajax and Dom are loaded and the event is not loaded; The third type loads all.

Mode 9: Static members
A static member is just a static property provided by a function or object, and can be classified as private and public, just as in C # or in Java, as in common static and private static.

Let's take a look at the public members, the public members are very simple, we usually declare methods, functions are public, such as:

The code is as follows Copy Code

Constructors
var Gadget = function () {
};

public static method
Gadget.isshiny = function () {
Return to "You Bet";
};

Normal method added on the prototype
Gadget.prototype.setPrice = function (price) {
This.price = Price;
};

Calling static methods
Console.log (Gadget.isshiny ()); "You Bet"

Create an instance, and then call the method
var iphone = new Gadget ();
Iphone.setprice (500);

Console.log (typeof Gadget.setprice); "Undefined"
Console.log (typeof Iphone.isshiny); "Undefined"
Gadget.prototype.isShiny = Gadget.isshiny;
Console.log (Iphone.isshiny ()); "You Bet"

and private static members, we can use its closure characteristics to implement, the following are the two implementation methods.

The first implementation method:

The code is as follows Copy Code

var Gadget = (function () {
Static Variables/Properties
var counter = 0;

New implementation of closure return constructor
return function () {
Console.log (counter + + 1);
};
} ()); Execute now

var g1 = new Gadget (); Logs 1
var g2 = new Gadget (); Logs 2
var g3 = new Gadget (); Logs 3

Can be seen, although each time is the object of new, but the number is still incremental, to achieve the purpose of static members.

The second way:

  code is as follows copy code

var Gadget = (function () {
Static Variables/Properties
var counter = 0,
Newgadget;

New constructor Implementation
Newgadget = function () {
Counter + 1;
};

Methods that authorization can access
NewGadget.prototype.getLastId = function () {
return counter;
};

overriding constructors
return newgadget;
} ()); Execute now

var iphone = new Gadget ();
Iphone.getlastid (); 1
var ipod = new Gadget ();
Ipod.getlastid (); 2
var ipad = new Gadget ();
Ipad.getlastid (); 3

The number is also incremented, which is implemented using the closure characteristics of its internal authorization method.

Summary
There are many patterns in JavaScript, and I've written 9 of them, which are pretty much the same for our day-to-day programming, and nine of different patterns that work differently in different scenarios.

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.