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

(完)

相关文章:

  • 2022-12-23
  • 2022-01-16
  • 2022-01-14
  • 2022-12-23
  • 2022-01-21
  • 2021-05-01
猜你喜欢
  • 2022-02-06
  • 2022-12-23
  • 2021-05-20
  • 2021-10-10
相关资源
相似解决方案