问题
obj1 = Object.create({}, { property: { enumerable: true, value: 42 } })
> obj1.property = 56
> 56
> obj1.property
> 42
with use strict there is an error.
I want to combine multiple objects: with jQuery.extend():
new_obj = $.extend(true, objN, obj1)
with ES6 Object.assign:
new_obj = Object.assign({}, objN, obj1)
In any case, the getter turns into a regular property, and therefore it can be changed. How to avoid it?
回答1:
You can write your own function that also copies over property attributes:
function extend(target, ...sources) {
for (let source of sources)
for (let key of Object.keys(source))
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
return target;
}
But notice there is good reason why Object.assign
does not, it could have weird effects if getters and setters are closures.
来源:https://stackoverflow.com/questions/37054596/js-es5-how-to-assign-objects-with-setters-and-getters