Javascript扩展了一个对象问题 [英] Javascript extending an object question
问题描述
我有以下代码:
this.myObject = {
key1: "val1",
key2: "val2"
}
this.aMethod = function (newObject) {
...
这里我想要一个新对象(可能是继承自 this.myObject
),其中包含<$ c中的所有内容$ c> this.myObject plus newObject
中的任何内容, newObject
应该覆盖 this.myObject中已有的字段
Here I want a new object (probably that inherits from this.myObject
) that contains everything in this.myObject
plus whatever is in newObject
also, fields in newObject
should override already existing fields in this.myObject
我该怎么做?
这个想法是 this.myObject
提供了一些默认值 - 但方法的用户可以覆盖这些值。我也批评这种整体模式。谢谢。
This idea is that this.myObject
provides some default values - but the user of the method can override these values. I'm open to criticisms of this overall "pattern" as well. Thanks.
推荐答案
SomeObject.prototype.someMethod = function() {
this.myObject = { key1: 1, key2: 2 };
this.aMethod = function (o) {
var newObject = object(this.myObject);
for (var prop in o) {
if (o.hasOwnProperty(prop)) {
newObject[prop] = o[prop];
}
}
// Now newObject contains all properties from the passed in object
// and also inherits all properties from myObject
};
};
注意:我正在使用来自@Marco答案的对象函数。
Note: I am using the object function from @Marco's answer.
这篇关于Javascript扩展了一个对象问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!