JavaScript对象创建模式详解
介绍
本篇主要探讨创建对象方面的模式下篇,运用各类技巧能显著减少错误并编写出极为精简的代码。
模式6:函数语法糖
函数语法糖旨在快速为对象添加方法,核心在于利用prototype特性。实现代码如下: 复制代码 代码如下: if (typeof Function.prototype.method !== "function") { Function.prototype.method = function (name, implementation) { this.prototype[name] = implementation; return this; }; } 在扩展对象时可这样使用: 复制代码 代码如下: var Person = function (name) { this.name = name; } .method('getName', function () { return this.name; }) .method('setName', function (name) { this.name = name; return this; }); 此举为Person函数添加了getName和setName两个方法,验证结果如下: 复制代码 代码如下: var a = new Person('Adam'); console.log(a.getName()); // 'Adam' console.log(a.setName('Eve').getName()); // 'Eve'
模式7:对象常量
对象常量体现为提供set、get、isDefined等方法的对象,其中set方法仅保留首次设置的值,后续设置无效,以此防止重载。实现代码如下: 复制代码 代码如下: var constant = (function () { var constants = {}, ownProp = Object.prototype.hasOwnProperty, // 只允许设置这三种类型的值 allowed = { string: 1, number: 1, boolean: 1 }, prefix = (Math.random() + "_").slice(2);
return { // 设置名称为name的属性 set: function (name, value) { if (this.isDefined(name)) { return false; } if (!ownProp.call(allowed, typeof value)) { return false; } constants[prefix + name] = value; return true; }, // 判断是否存在名称为name的属性 isDefined: function (name) { return ownProp.call(constants, prefix + name); }, // 获取名称为name的属性 get: function (name) { if (this.isDefined(name)) { return constants[prefix + name]; } return null; } }; } ());
验证代码如下: 复制代码 代码如下: // 检查是否存在 console.log(constant.isDefined("maxwidth")); // false
// 定义 console.log(constant.set("maxwidth", 480)); // true
// 重新检测 console.log(constant.isDefined("maxwidth")); // true
// 尝试重新定义 console.log(constant.set("maxwidth", 320)); // false
// 判断原先的定义是否还存在 console.log(constant.get("maxwidth")); // 480
模式8:沙盒模式
沙盒(Sandbox)模式为单个或多个模块提供独立上下文,互不干扰。例如Sandbox包含event、dom、ajax三个方法,调用其中两个组成的环境与调用三个组成的环境完全隔离。Sandbox实现代码如下: 复制代码 代码如下: function Sandbox() { // 将参数转为数组 var args = Array.prototype.slice.call(arguments), // 最后一个参数为callback callback = args.pop(), // 除最后一个参数外,其它均为要选择的模块 modules = (args[0] && typeof args[0] === "string") ? args : args[0], i;
// 强制使用new操作符 if (!(this instanceof Sandbox)) { return new Sandbox(modules, callback); }
// 添加属性 this.a = 1; this.b = 2;
// 向this对象上需想添加模块 // 如果没有模块或传入的参数为 "*" ,则以为着传入所有模块 if (!modules || modules == '*') { modules = []; for (i in Sandbox.modules) { if (Sandbox.modules.hasOwnProperty(i)) { modules.push(i); } } }
// 初始化需要的模块 for (i = 0; i < modules.length; i += 1) { Sandbox.modules[modules[i]](this); }
// 调用 callback callback(this); }
// 默认添加原型对象 Sandbox.prototype = { name: "My Application", version: "1.0", getName: function () { return this.name; } };
接着定义默认的初始模块:
复制代码 代码如下: 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 () { }; };
调用方式如下: 复制代码 代码如下: // 调用方式 Sandbox(['ajax', 'event'], function (box) { console.log(typeof (box.foo)); // 没有选择dom,所以box.foo不存在 });
Sandbox('ajax', 'dom', function (box) { console.log(typeof (box.attachEvent)); // 没有选择event,所以event里定义的attachEvent也不存在 });
Sandbox('*', function (box) { console.log(box); // 上面定义的所有方法都可访问 }); 通过三种不同调用方式可见,上下文环境各不相同:第一种无foo;第二种无attachEvent,因仅加载ajax和dom而未加载event;第三种加载了全部。
模式9:静态成员
静态成员(Static Members)是函数或对象提供的静态属性,分为私有和公有两类,类似C#或Java中的public static和private static。
先看公有成员,其声明简单,如平时声明的方法和函数均为公有,例如: 复制代码 代码如下: // 构造函数 var Gadget = function () { };
// 公有静态方法 Gadget.isShiny = function () { return "you bet"; };
// 原型上添加的正常方法 Gadget.prototype.setPrice = function (price) { this.price = price; };
// 调用静态方法 console.log(Gadget.isShiny()); // "you bet"
// 创建实例,然后调用方法 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"
私有静态成员可利用闭包特性实现,以下是两种实现方式。
第一种实现方式: 复制代码 代码如下: var Gadget = (function () { // 静态变量/属性 var counter = 0;
// 闭包返回构造函数的新实现 return function () { console.log(counter += 1); }; } ()); // 立即执行
var g1 = new Gadget(); // logs 1 var g2 = new Gadget(); // logs 2 var g3 = new Gadget(); // logs 3 尽管每次new出新对象,数字仍递增,实现了静态成员目的。
第二种方式: 复制代码 代码如下: var Gadget = (function () { // 静态变量/属性 var counter = 0, NewGadget;
//新构造函数实现 NewGadget = function () { counter += 1; };
// 授权可以访问的方法 NewGadget.prototype.getLastId = function () { return counter; };
// 覆盖构造函数 return NewGadget; } ()); // 立即执行
var iphone = new Gadget(); iphone.getLastId(); // 1 var ipod = new Gadget(); ipod.getLastId(); // 2 var ipad = new Gadget(); ipad.getLastId(); // 3 数字同样递增,这是利用内部授权方法的闭包特性实现的。
总结
这是对象创建模式的下篇,加上上篇共9种模式,是日常JavaScript编程中常用的对象创建方式。不同场景适用不同模式,请根据需求选择。