您的位置:首页 > 其它

学习 Douglas Crockford 的“原型式继承”

2010-01-07 17:27 232 查看
在《JavaScript高级程序设计(第2版)》和《JavaScript语言精粹》这两本书中都有这段代码:

Object.beget = function (o) {
  function F() {};
  F.prototype = o;
  return new F;
};

在函数中,定义了一个临时的构造函数,函数的参数 o 是传入的对象,它赋给了这个构造函数的原型。然后返回了实例。实质是传入的对象执行了一次浅拷贝。

优点:不用去创建构造函数。

缺点:引用类型的属性会共享其值。

如何解决这个缺点呢?在《JavaScript设计模式》的第4章中是用了工厂方式来创建引用类型值的childObject:

var CompoundObject = {};
CompoundObject.createChildObject = function(){
return {
num: [10]
};
}
Compound.childObject = CompoundObject.createChildObject();
var compoundObjectClone = Object.beget(CompoundObject);
compoundObjectClone.childObject = CompoundObject.createChildObject();
compoundObjectClone.childObject.num = [5];

childObject 是 CompoundObject 的子对象。通过 CompoundObject 的 createChildObject() 方法的返回值并赋给了它。compoundObjectClone 是 CompoundObject 的“原型式继承”的对象,它的 childObject 中的属性进行了重新的赋值定义。

(完)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: