introduce
This article mainly introduces the pattern of creating objects. Using various techniques can greatly avoid errors or write very streamlined code.
Pattern 1: Namespace
Namespaces can reduce the amount of global naming required to avoid naming conflicts or excessiveness. Generally, when we define the object level, it often looks like this:
The code copy is as follows:
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 levels, we must continue like this, which is very confusing. The namespace pattern exists to solve this problem. Let's look at the code:
The code copy is as follows:
// Insecure, it may overwrite existing MYAPP objects
var MYAPP = {};
// fine
if (typeof MYAPP === "undefined") {
var MYAPP = {};
}
// A simpler way
var MYAPP = MYAPP || {};
//Define common methods
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;
};
Calling the code is very simple:
The code copy is as follows:
// After namespace, 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 MYAPP
MYAPP.namespace('modules.module51');
// Very long name
MYAPP.namespace('once.upon.a.time.there.was.this.long.nested.property');
Pattern 2: Defining dependencies
Sometimes a module or function may refer to some third-party modules or tools. It is best to define these dependent modules at the beginning so that they can be easily replaced in the future.
The code copy is as follows:
var myFunction = function () {
// Depend on modules
var event = YAHOO.util.Event,
dom = YAHOO.util.dom;
// The local variables event and dom are used in the code after other functions
};
Pattern 3: Private properties and private methods
JavaScript does not provide specific syntax to support private properties and private methods, but we can implement it through closures, the code is as follows:
The code copy is as follows:
function Gadget() {
// Private object
var name = 'iPod';
// Public functions
this.getName = function () {
return name;
};
}
var toy = new Gadget();
// name is undefined and is private
console.log(toy.name); // undefined
// Public method access name
console.log(toy.getName()); // "iPod"
var myobj; // Assign values to myobj through self-executing function
(function () {
// Free object
var name = "my, oh my";
// Implement the public part, so there is no var
myobj = {
// Authorization method
getName: function () {
return name;
}
};
} ());
Mode 4: Revelation mode
It is also about hiding private methods, which is somewhat similar to the Module pattern in "In-depth understanding of JavaScript Series (3): Comprehensive analysis of Module Patterns", but it is not a return method, but a variable is declared externally and then assigned public methods to the variable internally. The code is as follows:
The code copy 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;
}
// Through assignment, all the details above are hidden
myarray = {
isArray: isArray,
indexOf: indexOf,
inArray: indexOf
};
} ());
//Test code
console.log(myarray.isArray([1, 2])); // true
console.log(myarray.isArray({ 0: 1 })); // false
console.log(myarray.indexOf(["a", "b", "z"], "z")); // 2
console.log(myarray.inArray(["a", "b", "z"], "z")); // 2
myarray.indexOf = null;
console.log(myarray.inArray(["a", "b", "z"], "z")); // 2
Mode 5: Chain Mode
Chain mode allows you to call an object method continuously, such as obj.add(1).remove(2).delete(4).add(2). The implementation idea is very simple, which is to return this as it is. The code is as follows:
The code copy 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);
}
};
// Chain method call
obj.increment().add(3).shout(); // 5
// Can also be called one by one
obj.increment();
obj.add(3);
obj.shout();
Summarize
This article is the previous article of the object creation mode, so stay tuned for the next article tomorrow.