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

在《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 中的属性进行了重新的赋值定义。

(完)

posted on 2010-01-07 17:27  豆豆の爸爸  阅读(1375)  评论(2编辑  收藏  举报