JavaScript: Object creation mode (Part 2)

Source: Internet
Author: User
Tags hasownproperty

JavaScript: Object creation mode (Part 2)
Introduction

This article mainly introduces the next article on Object creation mode. using various techniques, you can greatly avoid errors or write very simple code.

Mode 6: function syntax sugar

Function syntax sugar is an extension to quickly add a method (function) to an object. This mainly utilizes the prototype feature and the code is relatively simple. Let's first look at the implementation code:

if (typeof Function.prototype.method !== function) {    Function.prototype.method = function (name, implementation) {        this.prototype[name] = implementation;        return this;    };}

This can be used to extend an object:

var Person = function (name) {    this.name = name;}.method('getName',            function () {                return this.name;            }).method('setName', function (name) {    this.name = name;    return this;});

In this way, the getName and setName methods are added to the Person function. Next, let's verify the result:

var a = new Person('Adam');console.log(a.getName()); // 'Adam'console.log(a.setName('Eve').getName()); // 'Eve'
Mode 7: Object Constants

Object constants are the embodiment of various methods provided by a set, get, and ifDefined for an object. In addition, only the first set object is retained for the set method, and subsequent settings are invalid, it has reached the goal that others cannot reload. The implementation code is as follows:

Var constant = (function () {var constants = {}, ownProp = Object. prototype. hasOwnProperty, // only values of these three types can be set: allowed = {string: 1, number: 1, boolean: 1}, prefix = (Math. random () + _). slice (2); return {// set the property set: function (name, value) {if (this. isDefined (name) {return false;} if (! OwnProp. call (allowed, typeof value) {return false;} constants [prefix + name] = value; return true ;}, // determine whether the attribute isDefined with name exists: function (name) {return ownProp. call (constants, prefix + name) ;}, // get the property get: function (name) {if (this. isDefined (name) {return constants [prefix + name];} return null ;}};}());

The verification code is as follows:

// Check whether the console exists. log (constant. isDefined (maxwidth); // false // defines the console. log (constant. set (maxwidth, 480); // true // re-detect the console. log (constant. isDefined (maxwidth); // true // try to redefine the console. log (constant. set (maxwidth, 320); // false // checks whether the original definition still exists. log (constant. get (maxwidth); // 480.
Mode 8: Sandbox Mode

Sandbox mode provides a separate Context Environment for one or more modules without affecting the Context Environment of other modules. For example, a Sandbox contains three method events, dom and ajax, when two of the calls constitute an environment, there is no interference with the call environment. The Sandbox implementation code is as follows:

Function Sandbox () {// convert the parameter to an Array var args = Array. prototype. slice. call (arguments), // The last parameter is callback = args. pop (), // except the last parameter, all modules are required. modules = (args [0] & typeof args [0] === string )? Args: args [0], I; // force the use of the new operator if (! (This instanceof Sandbox) {return new Sandbox (modules, callback);} // Add the attribute this. a = 1; this. B = 2; // to this object, you need to add a module. // if there is no module or the input parameter is *, it means that if (! Modules | modules = '*') {modules = []; for (I in Sandbox. modules) {if (Sandbox. modules. hasOwnProperty (I) {modules. push (I) ;}}// initialize the required module for (I = 0; I <modules. length; I + = 1) {Sandbox. modules [modules [I] (this);} // call callback (this);} // Add the prototype Sandbox by default. prototype = {name: My Application, version: 1.0, getName: function () {return this. name ;}};

Then we define the default initial module:

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 call method is as follows:

// Call method Sandbox (['ajax ', 'event'], function (box) {console. log (typeof (box. foo); // No dom is 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 methods defined above can be accessed });

Three different call methods show that the context environments of the three methods are different. foo is not in the first method, and attachEvent is not in the second method, because only ajax and dom are loaded, but event is not loaded. The third method loads all.

Mode 9: static members

Static Members is only a static attribute provided by a function or object. It can be divided into private and public attributes, just like the public static and private Static attributes in C # or Java.

Let's take a look at the public members. The public members are very simple. The methods we declare at ordinary times, functions are all public, such:

// Constructor var Gadget = function () {}; // public static method Gadget. isShiny = function () {return you bet;}; // the normal method Gadget added on the prototype. prototype. setPrice = function (price) {this. price = price ;}; // call the static method 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); // undefinedconsole. log (typeof iphone. isShiny); // undefinedGadget. prototype. isShiny = Gadget. isShiny; console. log (iphone. isShiny (); // you bet

Private Static members can be implemented by using the closure feature. The following are two implementation methods.

The first implementation method:

Var Gadget = (function () {// static variable/attribute var counter = 0; // The closure returns the new Implementation of the constructor return function () {console. log (counter + = 1) ;};} (); // immediately execute var g1 = new Gadget (); // logs 1var g2 = new Gadget (); // logs 2var g3 = new Gadget (); // logs 3

It can be seen that although each object is a new object, the number is still increasing progressively, achieving the goal of static members.

Method 2:

Var Gadget = (function () {// static variable/attribute var counter = 0, NewGadget; // implement NewGadget = function () {counter + = 1 ;}; // authorize NewGadget. prototype. getLastId = function () {return counter ;}; // override constructor return NewGadget ;}(); // run var iphone = new Gadget (); iphone immediately. getLastId (); // 1var ipod = new Gadget (); ipod. getLastId (); // 2var ipad = new Gadget (); ipad. getLastId (); // 3

The number is also increasing, which is achieved by using the closure feature of its internal authorization method.

Summary

This is the next article on the object creation mode. The two articles have nine modes in total. They are the object creation mode that we often use in daily JavaScript programming. Different scenarios play different roles, we hope you can select the applicable mode based on your needs.

 

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.