1、Object.create( .. ) 创建关联:
Object.create(..) 是在 ES5 中新增的函数,所以在 ES5 之前的环境中(比如旧 IE)如
果要支持这个功能的话就需要使用一段简单的 polyfill 代码,它部分实现了 Object.create(..) 的功能:
if (!Object.create) {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
var anotherObject = {
a: 2
};
var myObject = Object.create(anotherObject, {
b: {
enumerable: false,
writable: true,
configurable: false,
value: 3
},
c: {
enumerable: true,
writable: false,
configurable: false,
value: 4
}
});
myObject.hasOwnProperty("a"); // false
myObject.hasOwnProperty("b"); // true
myObject.hasOwnProperty("c"); // true
myObject.a; // 2
myObject.b; // 3
myObject.c; // 4
Object.create(..) 的第二个参数指定了需要添加到新对象中的属性名以及这些属性的属性
描述符因为 ES5 之前的版本无法模拟属性操作符,所以 polyfill 代码无法
实现这个附加功能。
通常来说并不会使用 Object.create(..) 的附加功能,所以对于大多数开发者来说,上面
那段 polyfill 代码就足够了。
注意 :关联关系是备用
当你给开发者设计软件时,假设要调用 myObject.cool(),如果 myObject 中不存在 cool()
时这条语句也可以正常工作的话,那你的 API 设计就会变得很“神奇”,对于未来维护你
软件的开发者来说这可能不太好理解。
但是你可以让你的 API 设计不那么“神奇”,同时仍然能发挥 [[Prototype]] 关联的威力
var anotherObject = {
cool: function () {
console.log("cool!");
}
};
var myObject = Object.create(anotherObject);
myObject.doCool = function () {
this.cool(); // 内部委托!
};
myObject.doCool(); // "cool!"
这里我们调用的 myObject.doCool() 是实际存在于 myObject 中的,这可以让我们的 API 设
计更加清晰(不那么“神奇”)。从内部来说,我们的实现遵循的是委托设计模式,
通过 [[Prototype]] 委托到 anotherObject.cool()。
换句话说,内部委托比起直接委托可以让 API 接口设计更加清晰。下一章我们会详细解释
委托