【问题标题】:Copy and modify similar object for instantiation javascript复制和修改用于实例化 javascript 的类似对象
【发布时间】:2013-07-26 22:09:09
【问题描述】:

我有一个看起来像的对象

var customObject = function() {
    this.property = "value";
};

customObject.prototype = new otherObject();

customObject.prototype.property2 = function() {};

等等。 - 它比这大得多。

我可以通过写new customObject()成功实例化对象。

现在我想创建一个非常相似的对象,虽然有点不同。这涉及修改某些属性,甚至可能添加或删除一些属性。和上面的例子一样,我希望它可以通过写new customObject2()来调用。

我以为我可以这样做:

var customObject2 = new customObject();
customObject2.prototype = customObject.prototype;
customObject2.property = "modified value";

等等

但是,当我尝试通过执行 new customObject2() 来实例化它时,我收到一个错误,指出 customObject2 不是函数。

我希望我能很好地说明我想要创建的模式。我应该采取什么方法来创建这样的模式?

【问题讨论】:

  • 看看你的代码,你正在做customObject2 = new customObject()。这应该可以解释为什么它不是函数
  • 有什么快速的方法可以得到我需要的东西吗?或者我应该手动创建一个var customObject2 = function() {}; 并遍历原始customObject 的所有直接属性以将它们分配给customObject2this

标签: javascript design-patterns object


【解决方案1】:

如果customObject 不是主机对象(即,如果您尝试以与预期不同的方式调用它,不会给您非法调用错误)您可以将构造函数应用到不同的@987654323 @对象;

var customObject2 = function () {
    customObject.call(this); // construct as if `customObject`
    // now do more stuff
    this.anotherProperty = 'foo';
};
customObject2.prototype = Object.create(customObject.prototype);
    // inherit prototype but keep original safe

new customObject2();

向后兼容Object.create

function objectWithProto(proto) {
    var f;
    if (Object.create) return Object.create(proto);
    f = function () {};
    f.prototype = proto;
    return new f();
}

【讨论】:

  • 您是否有与旧浏览器兼容的 Object.create 替代方案?哦,等一下:stackoverflow.com/questions/5199126/…
  • 谢谢,这是我正在寻找的简短解决方案,它避免了简单地扩展 customObject
  • @user2180613 但这也是customObject的扩展,只是一种不同的技术。
  • @bfavaretto iirc coffeescript 将这种风格与他们的 extend 关键字一起使用
【解决方案2】:

我认为this should answer your question。基本上, new 关键字返回一个对象而不是函数。

【讨论】:

  • 不,它没有。我很清楚关键字的作用,但我想知道是否有一种快速的方法可以复制对象并使其保持“可实例化”。
【解决方案3】:

您为什么不使用第一次使用的相同公式?例如:

var customObject2 = function(){};
customObject2.prototype = new customObject();
customObject2.property = "modified value";
new customObject2(); // works!

customObject 的所有属性都将通过原型链被customObject2 的实例继承。

【讨论】:

  • 我不是在寻找继承。
猜你喜欢
  • 2022-11-21
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-03
  • 2015-07-11
相关资源
最近更新 更多