ES6中Object.assign()方法

对象的扩展

1.ES6中,对象的属性和方法可简写:对象的属性值可不写,前提是属性名已经声明;

    const name = "zhangsan";
    const password = "2222222";
    const obj = {
       name,
       password,
       arr:[1,2,3,4],
       sayName(){
          console.log(this.name);
       }
    };
    console.log(obj);
    var obj1 = {
       age:20,
    };

2.Object.assign()方法

特点:浅拷贝、对象属性的合并

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

var nObj = Object.assign({},obj,obj1);//花括号叫目标对象,后面的obj、obj1是源对象。对象合并是指:将源对象里面的属性添加到目标对象中去,若两者的属性名有冲突,后面的将会覆盖前面的

    // console.log(nObj);

    // obj.sayName();//zhangsan

    // nObj.sayName();//zhangsan

    nObj.name = "lisi";

    nObj.sayName = function(){

      console.log(this.name);

    };

    console.log(nObj);

    obj.sayName();//zhangsan

    nObj.sayName();//lisi

    nObj.arr[0] = 10;

    console.log(obj);//[10,2,3,4]

    console.log(nObj); //[10,2,3,4]

    //说明是浅拷贝,若要深拷贝,请考虑以前的方法(只是将源对象的引用给目标对象)

    //【注意】:当Object.assign()方法用于数组时:

     var arr11 = Object.assign([1,2,3],[4,5]);

     console.log(arr11);//[4,5,3]

     //[说明]:对象是根据属性名来对应,数组是根据索引号来对应,相当于

      var arr23 = {

         0:1,

         1:2,

         2:3

      };//相同的属性名有0、1,后面的覆盖前面的.

  

Object.assign()方法的用法

  1. 合并多个对象

  2. 克隆对象(浅);

  3. 为对象添加多个方法

  4. Object.assign(SomeClass.prototype, {
      someMethod(arg1, arg2) {
      },
      anotherMethod() {
      }
    });​
    // 原来的方法
    SomeClass.prototype.someMethod = function (arg1, arg2) {​
    };
    SomeClass.prototype.anotherMethod = function () {
    };

猜你喜欢

转载自blog.csdn.net/weixin_42158115/article/details/81258257