我有一个看起来像的物体
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不是函数。
我希望我能很好地说明我想要创建哪种模式。我应该采用什么方法来创建这种模式?
如果customObject
不是宿主对象(即,如果尝试以不同于预期的方式调用它,则不会给您带来非法调用错误),则可以将构造函数应用于其他this
Object;
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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句