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"); };
// 不安全,可能会覆盖已有的MYAPP对象 var MYAPP = {}; // 还好 if (typeof MYAPP === "undefined") { var MYAPP = {}; } // 更简洁的方式 var MYAPP = MYAPP || {}; //定义通用方法 MYAPP.namespace = function (ns_string) { var parts = ns_string.split('.'), parent = MYAPP, i; // 默认如果第一个节点是MYAPP的话,就忽略掉,比如MYAPP.ModuleA if (parts[0] === "MYAPP") { parts = parts.slice(1); } for (i = 0; i < parts.length; i += 1) { // 如果属性不存在,就创建 if (typeof parent[parts[i]] === "undefined") { parent[parts[i]] = {}; } parent = parent[parts[i]]; } return parent; };
// 通过namespace以后,可以将返回值赋给一个局部变量 var module2 = MYAPP.namespace('MYAPP.modules.module2'); console.log(module2 === MYAPP.modules.module2); // true // 跳过MYAPP MYAPP.namespace('modules.module51'); // 非常长的名字 MYAPP.namespace('once.upon.a.time.there.was.this.long.nested.property');
var myFunction = function () { // 依赖模块 var event = YAHOO.util.Event, dom = YAHOO.util.dom; // 其它函数后面的代码里使用局部变量event和dom };
function Gadget() { // 私有对象 var name = 'iPod'; // 公有函数 this.getName = function () { return name; }; } var toy = new Gadget(); // name未定义,是私有的 console.log(toy.name); // undefined // 公有方法访问name console.log(toy.getName()); // "iPod" var myobj; // 通过自执行函数给myobj赋值 (function () { // 自由对象 var name = "my, oh my"; // 实现了公有部分,所以没有var myobj = { // 授权方法 getName: function () { return name; } }; } ());
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; } //通过赋值的方式,将上面所有的细节都隐藏了 myarray = { isArray: isArray, indexOf: indexOf, inArray: indexOf }; } ()); //测试代码 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
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); } }; // 链方法调用 obj.increment().add(3).shout(); // 5 // 也可以单独一个一个调用 obj.increment(); obj.add(3); obj.shout();