ES6 學習筆記之對象的拓展

屬性的簡潔表示法

可以直接使用一個變數來初始化對象,變數名即屬性名,變數值即屬性值。

var foo = 'bar';  var baz = {foo};  console.log(baz);  // { foo: 'bar' }    // 等同於  var baz = {foo: foo};

另外一個例子

function f_es5(x, y) {    return { x: x, y: y };  }    function f_es6(x, y) {    return { x, y };  }    console.log(f_es5(1, 2));  // { x: 1, y: 2 }  console.log(f_es5(3, 4));  // { x: 3, y: 4 }

方法的簡潔表示法

ES6 簡潔方法後與一些面向對象的高級語言(如C++)差不多,函數名+參數+花括弧。另外注意簡潔寫法的屬性名是按字元串解析的。方法的屬性名可以是一些關鍵字,由於是按字元串來解析的,所以不會產生歧義。

var obj_es5 = {    'method': function () {      return 'Hello ES5 style.';    }  }    var obj_es6 = {    method() {      return 'Hello ES6 style.';    }  }    console.log(obj_es5.method());  console.log(obj_es6.method());

用表達式定義屬性名和方法名

ES5 中僅允許使用字面常量來定義屬性名和方法名,而 ES6 中允許使用表達式。比如兩個字元串拼接成一個方法名,如下所示:

var attrKey  = 'foo';  var funcName = 'show'    var obj = {    [attrKey]: true,    ['get' + 'Name']: 'Pency',    ['print' + 'Hello'] () { console.log('Hello!'); },    [`${funcName}Message`] () { console.log('Hi, this is a ES6 style function.'); }  }    console.log(obj.foo, obj.getName);  // true 'Pency'  obj.printHello();  // Hello!  obj.showMessage();  // Hi, this is a ES6 function.

Object.is() 方法

該方法用來彌補 == 和 === 的缺陷,可以嚴格對比兩個對象是否相等。

console.log(Object.is('foo', 'foo'));  // true  console.log(Object.is({}, {}));  // false  console.log(+0 === -0);  // true  console.log(NaN === NaN);  // false  console.log(Object.is(+0, -0));  // false  console.log(Object.is(NaN, NaN));  // true

從書中複製過來的 ES5 實現 Object.is 的實現

Object.defineProperty(Object, 'is', {    value: function(x, y) {      if (x === y) {        // 針對+0 不等於 -0的情況        return x !== 0 || 1 / x === 1 / y;      }      // 針對NaN的情況      return x !== x && y !== y;    },    configurable: true,    enumerable: false,    writable: true  });

Object.assign() 方法

var target = { a: 1, b: 1 };  var source1 = { b: 2, c: 2 };  var source2 = { c: 3 };    Object.assign(target, source1, source2);  console.log(target);  // { a: 1, b: 2, c: 3 }

Object.assign 常見的用法在書中也列舉了很多,我覺得非常實用,所以自己手抄一下給大家分享,更多請參考原著。

// 給對象添加屬性  class Point {    constructor(x, y) {      Object.assign(this, { x, y });    }  }    console.log(new Point(10, 20));  // Point { x: 10, y: 20 }
// 給對象添加方法  Object.assign(SomeClass.prototype, {    someMethod(arg1, arg2) {      // ...    },    anotherMethod() {      // ...    }  });    // 等同於下面的方式    SomeClass.prototype.someMethod = function (arg1, arg2) { /* ... */ };  SomeClass.prototype.anotherMethod = function () { /* ... */ };