【发布时间】: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的所有直接属性以将它们分配给customObject2的this?
标签: javascript design-patterns object