作用
Object.assign() 方法用於把一個或多個源對象的可枚舉屬性值復制到目標對象中,返回值為目標對象。
語法
Object.assign(target, ...sources)
參數
target: 目標對象
sources: 源對象
返回值
目標對象
描述
Object.assign 方法只復制源對象中可枚舉的屬性和對象自身的屬性。它在源對象上使用 [[Get]], 在目標對象上使用 [[Set]], 會調用 getter 和 setter。它不適合用於把一個包含 getter 的對象屬性合並到一個原型中。如果要把屬性定義連同可枚舉性復制到一個原型中,應該使用 Object.getOwnPropertyDescriptor() 和 Object.defineProperty() 方法。
String 和 Symbol 類型的屬性都會被復制。
當發生錯誤時,例如有一個屬性是不可寫的,將會拋出一個 TypeError 錯誤,目標對象保持不變。
注意 *Object.assign() * 源對象為 null 或 undefined 時不會報錯。
示例
克隆對象
var obj = {a: 1};
var copy = Object.assign({}, obj);
console.log(copy); // {a: 1};
合並對象
var o1 = {a: 1};
var o2 = {b: 2};
var o3 = {c: 3};
var obj = Object.assign(o1, o2, o3);
console.log(obj); //{a: 1, b: 2, c: 3}
console.log(o1); //{a: 1, b: 2, c: 3}, 目標對象被改變了
原型鏈上的屬性和不可枚舉的屬性無法復制
var obj = Object.create({foo: 1}, { // foo 在 obj 的原型鏈上
bar: {
value: 2 // bar 是一個不可枚舉的屬性.
},
baz: {
value: 3,
enumerable: true // baz 是 obj 自身的一個可枚舉屬性
}
});
var copy = Object.assign({}, obj);
console.log(copy); // { baz: 3 },原型鏈上的屬性和不可枚舉的屬性沒有復制到
傳遞原始類型
var v1 = 'abc';
var v2 = true;
var v3 = 10;
var v4 = Symbol('foo');
var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
//注意只有字符串類型的值有可枚舉屬性
console.log(obj); // { "0": "a", "1": "b", "2": "c" }
異常會中斷正在執行的復制任務
var target = Object.defineProperty({}, 'foo', {
value: 1,
writable: false
}); // target.foo 是一個只讀屬性
Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
// TypeError: "foo" is read-only
// 在分配 target.foo 時該異常被拋出
console.log(target.bar); // 2, 第一個源對象復制成功
console.log(target.foo2); // 3, 第二個源對象的第一個屬性復制成功
console.log(target.foo); // 1, 異常在這里拋出
console.log(target.foo3); // undefined, 任務已經結束, foo3 不會被復制 assign
console.log(target.baz); // undefined, 第三個源對象也不會被復制
有訪問器的情況
var obj = {
foo: 1,
get bar() {
return 2;
}
};
var copy = Object.assign({}, obj);
console.log(copy);
// { foo: 1, bar: 2 }, copy.bar 的值是 bar 的 getter 的返回值
ES5版本實現方法
if (typeof Object.assign != 'function') {
Object.assign = function(target) {
'use strict';
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object');
}
target = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source != null) {
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
}
return target;
};
}