1、是什么
Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象分配到目标对象。它将返回目标对象。
const a ={ name: '张三'}
const b ={
age: '18',
sex: '女'
}
const c = Object.assign(a,b)
console.log(c) // {name: '张三', age: '18', sex: '女'}
console.log(a) // {name: '张三', age: '18', sex: '女'}
console.log(a === c) // true
2、语法
Object.assign(target, ...sources)
3、注意点
let b = {
age: '18',
work:{
address: '广州',
time:'7.30am'
}
}
let c = Object.assign({}, b);
console.log(c); // { age: '18', work: {address: '广州', time: '7.30am'}}
c.work.address = '北京'
c.age = '22'
console.log(c); // { age: '22', work: {address: '北京', time: '7.30am'}}
console.log(b); // {{age: '18', work: {address: '北京', time: '7.30am'}}
const a ={ name: '张三'}
const b ={name: '李四'}
const c = {name: '王五'}
Object.assign(a,b,c)
console.log(a)
// {name: '王五'}
const a ={ name: '张三'}
let b = {
a1: Symbol("SymbolValue"),
a2: null,
a3: undefined
}
let c = Object.assign(a, b);
console.log(c);
//{name: '张三', a1: Symbol(SymbolValue), a2: null, a3: undefined}
let userInfo = {}
Object.defineProperty(userInfo, "work", {
adrress: '广州',
// enumerable: false // Object.defineProperty默认就是不可枚举的属性fase
});
Object.defineProperty(userInfo, "time", {
value: '11.am',
enumerable: true
});
let c = Object.assign({}, userInfo);
console.log(c);
// {time: '11.am'}
let userInfo = {}
Object.defineProperty(userInfo, "time", {
value: '11.am',
writable: false
});
let c = Object.assign(userInfo , {time: '18.pm'});
console.log(c);
// VM586:6 Uncaught TypeError: Cannot assign to read only property 'time' of object '#