讀es6 語法記錄相關知識點--對象新增的方法

對象新增的方法

  • Object.is()

ES5 比較兩個值是否相等,只有兩個運算符:相等運算符()和嚴格相等運算符(=)。它們都有缺點,前者會自動轉換數據類型,後者的NaN不等於自身,以及+0等於-0。JavaScript
缺乏一種運算,在所有環境中,只要兩個值是一樣的,它們就應該相等。

Object.is用來比較兩個值是否嚴格相等,與嚴格比較運算符(===)的行爲基本一致。
不同之處只有兩個:一是+0不等於-0,二是NaN等於自身。

+0 === -0 //true
NaN === NaN // false

Object.is(+0, -0) // false
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()
    Object.assign方法用於對象的合併,將源對象(source)的所有可枚舉屬性,複製到目標對象(target)。
const target = { a: 1 };

const source1 = { b: 2 };
const source2 = { c: 3 };

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

Object.assign方法的第一個參數是目標對象,後面的參數都是源對象。

注意,如果目標對象與源對象有同名屬性,或多個源對象有同名屬性,則後面的屬性會覆蓋前面的屬性。

const target = { a: 1, b: 1 };

const source1 = { b: 2, c: 2 };
const source2 = { c: 3 };

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

如果只有一個參數,Object.assign會直接返回該參數。

const obj = {a: 1};
Object.assign(obj) === obj // true

如果該參數不是對象,則會先轉成對象,然後返回。

typeof Object.assign(2) // "object"

由於undefined和null無法轉成對象,所以如果它們作爲參數,就會報錯。

Object.assign(undefined) // 報錯
Object.assign(null) // 報錯

如果非對象參數出現在源對象的位置(即非首參數),那麼處理規則有所不同。首先,這些參數都會轉成對象,如果無法轉成對象,就會跳過。這意味着,如果undefined和null不在首參數,就不會報錯。

let obj = {a: 1};
Object.assign(obj, undefined) === obj // true
Object.assign(obj, null) === obj // true

其他類型的值(即數值、字符串和布爾值)不在首參數,也不會報錯。但是,除了字符串會以數組形式,拷貝入目標對象,其他值都不會產生效果。

const v1 = 'abc';
const v2 = true;
const v3 = 10;

const obj = Object.assign({}, v1, v2, v3);
console.log(obj); // { "0": "a", "1": "b", "2": "c" }

上面代碼中,v1、v2、v3分別是字符串、布爾值和數值,結果只有字符串合入目標對象(以字符數組的形式),數值和布爾值都會被忽略。這是因爲只有字符串的包裝對象,會產生可枚舉屬性。

Object(true) // {[[PrimitiveValue]]: true}
Object(10)  //  {[[PrimitiveValue]]: 10}
Object('abc') // {0: "a", 1: "b", 2: "c", length: 3, [[PrimitiveValue]]: "abc"}

上面代碼中,布爾值、數值、字符串分別轉成對應的包裝對象,可以看到它們的原始值都在包裝對象的內部屬性[[PrimitiveValue]]上面,這個屬性是不會被Object.assign拷貝的。只有字符串的包裝對象,會產生可枚舉的實義屬性,那些屬性則會被拷貝。

Object.assign拷貝的屬性是有限制的,只拷貝源對象的自身屬性(不拷貝繼承屬性),也不拷貝不可枚舉的屬性(enumerable: false)。
屬性名爲 Symbol 值的屬性,也會被Object.assign拷貝。

Object.assign({ a: 'b' }, { [Symbol('c')]: 'd' })
// { a: 'b', Symbol(c): 'd' }

Object.assign() 注意點

  1. 淺拷貝
    Object.assign方法實行的是淺拷貝,而不是深拷貝。也就是說,如果源對象某個屬性的值是對象,那麼目標對象拷貝得到的是這個對象的引用。
const obj1 = {a: {b: 1}};
const obj2 = Object.assign({}, obj1);

obj1.a.b = 2;
obj2.a.b // 2
  1. 同名屬性的替換
    對於這種嵌套的對象,一旦遇到同名屬性,Object.assign的處理方法是替換,而不是添加。
const target = { a: { b: 'c', d: 'e' } }
const source = { a: { b: 'hello' } }
Object.assign(target, source)
// { a: { b: 'hello' } }

上面代碼中,target對象的a屬性被source對象的a屬性整個替換掉了,而不會得到{ a: { b: ‘hello’, d: ‘e’ } }的結果。這通常不是開發者想要的,需要特別小心。

  1. 數組的處理
    Object.assign只能進行值的複製,如果要複製的值是一個取值函數,那麼將求值後再複製。
const source = {
  get foo() { return 1 }
};
const target = {};

Object.assign(target, source)
// { foo: 1 }

上面代碼中,source對象的foo屬性是一個取值函數,Object.assign不會複製這個取值函數,只會拿到值以後,將這個值複製過去。

常見用途

  1. 爲對象添加屬性
class Point {
  constructor(x, y) {
    Object.assign(this, {x, y});
  }
}

上面方法通過Object.assign方法,將x屬性和y屬性添加到Point類的對象實例。

  1. 爲對象添加方法
Object.assign(SomeClass.prototype, {
  someMethod(arg1, arg2) {
    ···
  },
  anotherMethod() {
    ···
  }
});

// 等同於下面的寫法
SomeClass.prototype.someMethod = function (arg1, arg2) {
  ···
};
SomeClass.prototype.anotherMethod = function () {
  ···
};

上面代碼使用了對象屬性的簡潔表示法,直接將兩個函數放在大括號中,再使用assign方法添加到SomeClass.prototype之中。

  1. 克隆對象
function clone(origin) {
  return Object.assign({}, origin);
}

上面代碼將原始對象拷貝到一個空對象,就得到了原始對象的克隆。
不過,採用這種方法克隆,只能克隆原始對象自身的值,不能克隆它繼承的值。如果想要保持繼承鏈,可以採用下面的代碼。

function clone(origin) {
  let originProto = Object.getPrototypeOf(origin);
  return Object.assign(Object.create(originProto), origin);
}
  1. 合併多個對象
    將多個對象合併到某個對象。
const merge =
  (target, ...sources) => Object.assign(target, ...sources);

如果希望合併後返回一個新對象,可以改寫上面函數,對一個空對象合併。

const merge =
  (...sources) => Object.assign({}, ...sources);
  1. 爲屬性指定默認值
const DEFAULTS = {
  logLevel: 0,
  outputFormat: 'html'
};

function processContent(options) {
  options = Object.assign({}, DEFAULTS, options);
  console.log(options);
  // ...
}

上面代碼中,DEFAULTS對象是默認值,options對象是用戶提供的參數。Object.assign方法將DEFAULTS和options合併成一個新對象,如果兩者有同名屬性,則options的屬性值會覆蓋DEFAULTS的屬性值。

注意,由於存在淺拷貝的問題,DEFAULTS對象和options對象的所有屬性的值,最好都是簡單類型,不要指向另一個對象。否則,DEFAULTS對象的該屬性很可能不起作用。

const DEFAULTS = {
  url: {
    host: 'example.com',
    port: 7070
  },
};

processContent({ url: {port: 8000} })
// {
//   url: {port: 8000}
// }

上面代碼的原意是將url.port改成 8000,url.host不變。實際結果卻是options.url覆蓋掉DEFAULTS.url,所以url.host就不存在了。

  • Object.getOwnPropertyDescriptors()
    ES5 的Object.getOwnPropertyDescriptor()方法會返回某個對象屬性的描述對象(descriptor)。ES2017 引入了Object.getOwnPropertyDescriptors()方法,返回指定對象所有自身屬性(非繼承屬性)的描述對象。
const obj = {
  foo: 123,
  get bar() { return 'abc' }
};

Object.getOwnPropertyDescriptors(obj)
// { foo:
//    { value: 123,
//      writable: true,
//      enumerable: true,
//      configurable: true },
//   bar:
//    { get: [Function: get bar],
//      set: undefined,
//      enumerable: true,
//      configurable: true } }

上面代碼中,Object.getOwnPropertyDescriptors()方法返回一個對象,所有原對象的屬性名都是該對象的屬性名,對應的屬性值就是該屬性的描述對象。

該方法的實現非常容易。

function getOwnPropertyDescriptors(obj) {
  const result = {};
  for (let key of Reflect.ownKeys(obj)) {
    result[key] = Object.getOwnPropertyDescriptor(obj, key);
  }
  return result;
}

該方法的引入目的,主要是爲了解決Object.assign()無法正確拷貝get屬性和set屬性的問題。

const source = {
  set foo(value) {
    console.log(value);
  }
};

const target1 = {};
Object.assign(target1, source);

Object.getOwnPropertyDescriptor(target1, 'foo')
// { value: undefined,
//   writable: true,
//   enumerable: true,
//   configurable: true }

上面代碼中,source對象的foo屬性的值是一個賦值函數,Object.assign方法將這個屬性拷貝給target1對象,結果該屬性的值變成了undefined。這是因爲Object.assign方法總是拷貝一個屬性的值,而不會拷貝它背後的賦值方法或取值方法。

這時,Object.getOwnPropertyDescriptors()方法配合Object.defineProperties()方法,就可以實現正確拷貝。

const source = {
  set foo(value) {
    console.log(value);
  }
};

const target2 = {};
Object.defineProperties(target2, Object.getOwnPropertyDescriptors(source));
Object.getOwnPropertyDescriptor(target2, 'foo')
// { get: undefined,
//   set: [Function: set foo],
//   enumerable: true,
//   configurable: true }

上面代碼中,兩個對象合併的邏輯可以寫成一個函數。

const shallowMerge = (target, source) => Object.defineProperties(
  target,
  Object.getOwnPropertyDescriptors(source)
);

Object.getOwnPropertyDescriptors()方法的另一個用處,是配合Object.create()方法,將對象屬性克隆到一個新對象。這屬於淺拷貝。

const clone = Object.create(Object.getPrototypeOf(obj),
  Object.getOwnPropertyDescriptors(obj));

// 或者

const shallowClone = (obj) => Object.create(
  Object.getPrototypeOf(obj),
  Object.getOwnPropertyDescriptors(obj)
);

上面代碼會克隆對象obj。

另外,Object.getOwnPropertyDescriptors()方法可以實現一個對象繼承另一個對象。以前,繼承另一個對象,常常寫成下面這樣。

const obj = {
  __proto__: prot,
  foo: 123,
};

ES6 規定__proto__只有瀏覽器要部署,其他環境不用部署。如果去除__proto__,上面代碼就要改成下面這樣。

const obj = Object.create(prot);
obj.foo = 123;

// 或者

const obj = Object.assign(
  Object.create(prot),
  {
    foo: 123,
  }
);

有了Object.getOwnPropertyDescriptors(),我們就有了另一種寫法。

const obj = Object.create(
  prot,
  Object.getOwnPropertyDescriptors({
    foo: 123,
  })
);

Object.getOwnPropertyDescriptors()也可以用來實現 Mixin(混入)模式。

let mix = (object) => ({
  with: (...mixins) => mixins.reduce(
    (c, mixin) => Object.create(
      c, Object.getOwnPropertyDescriptors(mixin)
    ), object)
});

// multiple mixins example
let a = {a: 'a'};
let b = {b: 'b'};
let c = {c: 'c'};
let d = mix(c).with(a, b);

d.c // "c"
d.b // "b"
d.a // "a"

上面代碼返回一個新的對象d,代表了對象a和b被混入了對象c的操作。

  • __proto__屬性
    __proto__屬性(前後各兩個下劃線),用來讀取或設置當前對象的prototype對象。目前,所有瀏覽器(包括 IE11)都部署了這個屬性。
// es5 的寫法
const obj = {
  method: function() { ... }
};
obj.__proto__ = someOtherObj;

// es6 的寫法
var obj = Object.create(someOtherObj);
obj.method = function() { ... };

無論從語義的角度,還是從兼容性的角度,都不要使用這個屬性,而是使用下面的Object.setPrototypeOf()(寫操作)、Object.getPrototypeOf()(讀操作)、Object.create()(生成操作)代替。

  • Object.setPrototypeOf()
    Object.setPrototypeOf方法的作用與__proto__相同,用來設置一個對象的prototype對象,返回參數對象本身。它是 ES6 正式推薦的設置原型對象的方法。
// 格式
Object.setPrototypeOf(object, prototype)

// 用法
const o = Object.setPrototypeOf({}, null);

該方法等同於下面的函數。

function setPrototypeOf(obj, proto) {
  obj.__proto__ = proto;
  return obj;
}

下面是一個例子。

let proto = {};
let obj = { x: 10 };
Object.setPrototypeOf(obj, proto);

proto.y = 20;
proto.z = 40;

obj.x // 10
obj.y // 20
obj.z // 40

上面代碼將proto對象設爲obj對象的原型,所以從obj對象可以讀取proto對象的屬性。

如果第一個參數不是對象,會自動轉爲對象。但是由於返回的還是第一個參數,所以這個操作不會產生任何效果。

Object.setPrototypeOf(1, {}) === 1 // true
Object.setPrototypeOf('foo', {}) === 'foo' // true
Object.setPrototypeOf(true, {}) === true // true

由於undefined和null無法轉爲對象,所以如果第一個參數是undefined或null,就會報錯。

Object.setPrototypeOf(undefined, {})
// TypeError: Object.setPrototypeOf called on null or undefined

Object.setPrototypeOf(null, {})
// TypeError: Object.setPrototypeOf called on null or undefined
  • Object.getPrototypeOf()
    該方法與Object.setPrototypeOf方法配套,用於讀取一個對象的原型對象。
Object.getPrototypeOf(obj);

下面是一個例子。

function Rectangle() {
  // ...
}

const rec = new Rectangle();

Object.getPrototypeOf(rec) === Rectangle.prototype
// true

Object.setPrototypeOf(rec, Object.prototype);
Object.getPrototypeOf(rec) === Rectangle.prototype
// false

如果參數不是對象,會被自動轉爲對象。

// 等同於 Object.getPrototypeOf(Number(1))
Object.getPrototypeOf(1)
// Number {[[PrimitiveValue]]: 0}

// 等同於 Object.getPrototypeOf(String('foo'))
Object.getPrototypeOf('foo')
// String {length: 0, [[PrimitiveValue]]: ""}

// 等同於 Object.getPrototypeOf(Boolean(true))
Object.getPrototypeOf(true)
// Boolean {[[PrimitiveValue]]: false}

Object.getPrototypeOf(1) === Number.prototype // true
Object.getPrototypeOf('foo') === String.prototype // true
Object.getPrototypeOf(true) === Boolean.prototype // true

如果參數是undefined或null,它們無法轉爲對象,所以會報錯。

Object.getPrototypeOf(null)
// TypeError: Cannot convert undefined or null to object

Object.getPrototypeOf(undefined)
// TypeError: Cannot convert undefined or null to object
  • Object.keys(),Object.values(),Object.entries()
    Object.keys()
    ES5 引入了Object.keys方法,返回一個數組,成員是參數對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵名。
var obj = { foo: 'bar', baz: 42 };
Object.keys(obj)
// ["foo", "baz"]

ES2017 引入了跟Object.keys配套的Object.values和Object.entries,作爲遍歷一個對象的補充手段,供for…of循環使用。

let {keys, values, entries} = Object;
let obj = { a: 1, b: 2, c: 3 };

for (let key of keys(obj)) {
  console.log(key); // 'a', 'b', 'c'
}

for (let value of values(obj)) {
  console.log(value); // 1, 2, 3
}

for (let [key, value] of entries(obj)) {
  console.log([key, value]); // ['a', 1], ['b', 2], ['c', 3]
}

Object.values()
Object.values方法返回一個數組,成員是參數對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵值。

const obj = { foo: 'bar', baz: 42 };
Object.values(obj)
// ["bar", 42]

返回數組的成員順序,與本章的《屬性的遍歷》部分介紹的排列規則一致。
Object.values只返回對象自身的可遍歷屬性。

const obj = Object.create({}, {p: {value: 42}});
Object.values(obj) // []

上面代碼中,Object.create方法的第二個參數添加的對象屬性(屬性p),如果不顯式聲明,默認是不可遍歷的,因爲p的屬性描述對象的enumerable默認是false,Object.values不會返回這個屬性。只要把enumerable改成true,Object.values就會返回屬性p的值。

const obj = Object.create({}, {p:
  {
    value: 42,
    enumerable: true
  }
});
Object.values(obj) // [42]

Object.values會過濾屬性名爲 Symbol 值的屬性。

Object.values({ [Symbol()]: 123, foo: 'abc' });
// ['abc']

如果Object.values方法的參數是一個字符串,會返回各個字符組成的一個數組。

Object.values('foo')
// ['f', 'o', 'o']

上面代碼中,字符串會先轉成一個類似數組的對象。字符串的每個字符,就是該對象的一個屬性。因此,Object.values返回每個屬性的鍵值,就是各個字符組成的一個數組。

如果參數不是對象,Object.values會先將其轉爲對象。由於數值和布爾值的包裝對象,都不會爲實例添加非繼承的屬性。所以,Object.values會返回空數組。

Object.values(42) // []
Object.values(true) // []

Object.entries()
Object.entries()方法返回一個數組,成員是參數對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵值對數組。

const obj = { foo: 'bar', baz: 42 };
Object.entries(obj)
// [ ["foo", "bar"], ["baz", 42] ]

除了返回值不一樣,該方法的行爲與Object.values基本一致。
如果原對象的屬性名是一個 Symbol 值,該屬性會被忽略。

Object.entries({ [Symbol()]: 123, foo: 'abc' });
// [ [ 'foo', 'abc' ] ]

Object.entries方法的另一個用處是,將對象轉爲真正的Map結構。

const obj = { foo: 'bar', baz: 42 };
const map = new Map(Object.entries(obj));
map // Map { foo: "bar", baz: 42 }
  • Object.fromEntries()
    Object.fromEntries()方法是Object.entries()的逆操作,用於將一個鍵值對數組轉爲對象。
Object.fromEntries([
  ['foo', 'bar'],
  ['baz', 42]
])
// { foo: "bar", baz: 42 }

該方法的主要目的,是將鍵值對的數據結構還原爲對象,因此特別適合將 Map 結構轉爲對象。

// 例一
const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);

Object.fromEntries(entries)
// { foo: "bar", baz: 42 }

// 例二
const map = new Map().set('foo', true).set('bar', false);
Object.fromEntries(map)
// { foo: true, bar: false }

該方法的一個用處是配合URLSearchParams對象,將查詢字符串轉爲對象。

Object.fromEntries(new URLSearchParams('foo=bar&baz=qux'))
// { foo: "bar", baz: "qux" }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章