JavaScript: Object creation mode (Part 1)
Introduction
This article describes how to create objects. using various techniques, you can avoid errors or write very simple code.
Mode 1: namespace)
The namespace can reduce the number of global names required to avoid name conflicts or excessive. This is often the case when we define the object hierarchy:
var app = app || {};app.moduleA = app.moduleA || {};app.moduleA.subModule = app.moduleA.subModule || {};app.moduleA.subModule.MethodA = function () { console.log(print A);};app.moduleA.subModule.MethodB = function () { console.log(print B);};
If there are many layers, it will continue like this and it is very messy. The namespace mode exists to solve this problem. Let's look at the Code:
// Insecure. It may overwrite the existing MYAPP object var MYAPP ={}; // if (typeof MYAPP ===undefined) {var MYAPP = {};} // more concise method var MYAPP = MYAPP ||{}; // defines the general method MYAPP. namespace = function (ns_string) {var parts = ns_string.split ('. '), parent = MYAPP, I; // by default, if the first node is MYAPP, it will be ignored, such as MYAPP. moduleA if (parts [0] === MYAPP) {parts = parts. slice (1) ;}for (I = 0; I <parts. length; I + = 1) {// if the property does not exist, create if (typeof parent [parts [I] === undefined) {parent [parts [I] ={};} parent = parent [parts [I] ;}return parent ;};
The call code is very simple:
// After namespace is used, the return value can be assigned to a local variable var module2 = MYAPP. namespace ('myapp. modules. module2'); console. log (module2 === MYAPP. modules. module2); // true // skip MYAPPMYAPP. namespace ('modules. module51'); // a very long name, MYAPP. namespace ('Once. upon. a. time. there. was. this. long. nested. properties ');
Mode 2: define dependency
Sometimes a module or function may reference some third-party modules or tools. At this time, it is best to define these dependent modules at the beginning, this can be easily replaced in the future.
Var myFunction = function () {// dependent module var event = YAHOO. util. event, dom = YAHOO. util. dom; // use the local variables event and dom in the code behind other functions };
Mode 3: Private attributes and private methods
JavaScript book does not provide specific syntax to support private attributes and private methods, but we can implement it through closures. The Code is as follows:
Function Gadget () {// Private object var name = 'ipod '; // public function this. getName = function () {return name ;};} var toy = new Gadget (); // the name is not defined and is a private console. log (toy. name); // undefined // use a public method to access the nameconsole. log (toy. getName (); // iPodvar myobj; // assign a value to myobj through the self-executed function () {// free object var name = my, oh my; // implements the public part, so there is no var myobj ={// authorization method getName: function () {return name ;}};}());
Mode 4: Revelation Mode
The Mode for hiding private methods is similar to the Module mode in "Deeply Understanding JavaScript series (3): Fully parsing Module mode", but it is not the return mode, instead, declare a variable externally and assign a public method to the variable internally. The Code is as follows:
Var myarray; (function () {var astr = [object Array], toString = Object. prototype. toString; function isArray (a) {return toString. call (a) === astr;} function indexOf (haystack, needle) {var I = 0, max = haystack. length; for (; I <max; I + = 1) {if (haystack [I] === needle) {return I ;}} return-1 ;} // by assigning values, all the above details are hidden from myarray = {isArray: isArray, indexOf: indexOf, inArray: indexOf };}()); // test the code console. log (myarray. isArray ([1, 2]); // trueconsole. log (myarray. isArray ({0: 1}); // falseconsole. log (myarray. indexOf ([a, B, z], z); // 2console. log (myarray. inArray ([a, B, z], z); // 2myarray. indexOf = null; console. log (myarray. inArray ([a, B, z], z); // 2
Mode 5: Chain Mode
In the chain mode, you can call methods of an object consecutively, such as obj. add (1 ). remove (2 ). delete (4 ). in the form of add (2), the Implementation idea is very simple, that is, to return this as is. The Code is as follows:
Var obj = {value: 1, increment: function () {this. value + = 1; return this;}, add: function (v) {this. value + = v; return this;}, shout: function () {console. log (this. value) ;}}; // call obj. increment (). add (3 ). shout (); // 5 // you can also call obj one by one. increment (); obj. add (3); obj. shout ();