Object.assign对象的拷贝与合并

let target={a:1}
let source1={b:2}
let source2={c:3}

Object.assgin{target,source1,source2}

console.log(target)

如果目标对象有同名属性,或多个源对象有同名属性,后面的属性会覆盖前面的属性。

let target={a:1,b:2}
let source1={b:3,c:3}
let source2={c:4}

Object.assign(target,source1,source2)

如果只有一个目标对象,直接返回该参数

let target={a:1}
Object.assgin(target)
console.log(target)

如果目标对象不是一个对象,先转成对象

let abc=Object.assgin("abc")

console.log(abc[0],abc[1],abc[2])

 目标对象不能是undefined和null

Object.assgin(undefined)
Object.assgin(null)

为对象添加属性

function Person(name,age){
    Object.assgin(this,{name:name,age:age})

    //相当于
    this.name=name
    this.age=age
}

let person=new Person("张三",20)
console.log(person.name,person.age)

为对象添加方法

Object.assign(Person.protoType,{
    say(){
            console.log("say()方法")
        },
    run(){
            console.log("run()方法")
        }
    })

person.say()
person.run()

猜你喜欢

转载自blog.csdn.net/qq_26798533/article/details/119479474