gpt4 book ai didi

Javascript extending an object 问题

转载 作者:搜寻专家 更新时间:2023-11-01 05:02:46 25 4
gpt4 key购买 nike

我有以下代码:

this.myObject = {
key1: "val1",
key2: "val2"
}

this.aMethod = function (newObject) {
...

我想要一个新对象(可能继承自 this.myObject),它包含 this.myObject 中的所有内容 plus newObject 此外,newObject 中的字段应该覆盖 this.myObject

中已有的字段

我该怎么做?

这个想法是 this.myObject 提供了一些默认值——但是该方法的用户可以覆盖这些值。我也愿意接受对这种整体“模式”的批评。谢谢。

最佳答案

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 回答中的对象函数。

关于Javascript extending an object 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4154712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com