在 JavaScript 中扩展具有多个属性的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5585168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:41:19  来源:igfitidea点击:

Extending an object with multiple properties in JavaScript

javascriptobject

提问by user385411

I have a global JavaScript object with multiple properties and functions that I am creating it this way:

我有一个具有多个属性和函数的全局 JavaScript 对象,我以这种方式创建它:

myObject = {};

I thought that I can easily extend this object by creating something like this

我认为我可以通过创建这样的东西来轻松扩展这个对象

myObject = { propA1 : null, ....., propAN : null};

instead of

代替

myObject.propA1 = null;
myObject......;
myObject.propAN = null;

What's wrong with my approach?

我的方法有什么问题?

回答by SLaks

When you write myObject = { ... }, you're creating a brand-new object and setting myObjectto point to it.
The previous value of myObjectis thrown away.

当您编写 时myObject = { ... },您正在创建一个全新的对象并设置myObject指向它。
之前的值myObject被丢弃。

Instead, you can use jQuery:

相反,您可以使用 jQuery:

jQuery.extend(myObject, { newProperty: whatever });

回答by beatgammit

Without jQuery, you could create an array of objects with something like this:

如果没有 jQuery,您可以使用以下内容创建一个对象数组:

[{'key': 'atuhoetu', 'value': 'uehtnehatn'},{...}]

If you don't care about compatibility, recent browsers should support this:

如果你不关心兼容性,最近的浏览器应该支持这个:

var newObj = {prop1: 'val', prop2: 'val'};
Object.keys(newObj).forEach(function (item) {
    myObject[item] = newObj[item];
});

This will iterate over all items in newObject and add them to myObj.

这将遍历 newObject 中的所有项目并将它们添加到 myObj。

回答by Patricio Córdova

Or, something cleaner:

或者,更干净的东西:

function extend(target, source){
    for(prop in source){
        target[prop] = source[prop];
    }
}

If you use it the following way:

如果您按以下方式使用它:

var objA = {a: "a"};
var objB = {b: "b", c: "c"};
extend(objA, objB);

The result will be:

结果将是:

objA = {a: "a", b: "b", c: "c"};