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 () {
    };
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章