ES6中對象新增的方法

Object

一、概覽

  1. Object.is()
  2. Object.assign()
  3. Object.getOwnPropertyDescriptors()
  4. __proto__屬性
  5. Object.getPrototypeOf()
  6. Object.setPrototypeOf()
  7. Object.keys()
  8. Object.values()
  9. Object.entries()
  10. Object.fromEntries()

Object.is()

ES5中的=====都可以用來判斷兩個值是否相等,但是都有缺陷,==會自動進行隱式類型轉換,===NaN不等于自身及+0不等于-0
Object.is()引入的目的就是為了保證在所有環境中,只要兩個值是一樣的,它們就應該相等,其行為與===基本一致,用來比較兩個值是否嚴格相等。

Object.is('foo', 'foo')
// true
Object.is({}, {})
// false

有兩個不同之處:一是+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}

基本用法

  • 后面的屬性會覆蓋前面相同的屬性:
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}
  • 如果只有一個參數,直接返回該參數:
const obj = {a: 1};
Object.assign(obj) === obj // true
  • 如果該參數不是對象,則會先轉成對象,然后返回:
typeof Object.assign(2) // "object"
  • 由于undefinednull無法轉成對象,所以如果它們作為參數,就會報錯:
Object.assign(undefined) // 報錯
Object.assign(null) // 報錯
  • 但是如果undefinednull都不在首參數,就不會報錯:
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" }

上述代碼中數值和布爾值都會被忽略。這是因為只有字符串的包裝對象,會產生可枚舉屬性。

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):
Object.assign({b: 'c'},
  Object.defineProperty({}, 'invisible', {
    enumerable: false,
    value: 'hello'
  })
)
// { b: 'c' }

上述需要拷貝的對象只有一個不可枚舉屬性invisible,所以這個屬性并沒有被拷貝進去。

  • 屬性名為 Symbol 值的屬性,也會被拷貝:
Object.assign({ a: 'b' }, { [Symbol('c')]: 'd' })
// { a: 'b', Symbol(c): 'd' }

注意點

  • 淺拷貝
const obj1 = {a: {b: 1}};
const obj2 = Object.assign({}, obj1);

obj1.a.b = 2;
obj2.a.b // 2
  • 同名屬性的替換
const target = { a: { b: 'c', d: 'e' } }
const source = { a: { b: 'hello' } }
Object.assign(target, source)
// { a: { b: 'hello' } }

上述代碼中,a被整個替換,不會得到{ a: { b: 'hello', d: 'e' } }這樣的結果。

  • 數組的處理
Object.assign([1, 2, 3], [4, 5])
// [4, 5, 3]

上述代碼中,以后一個數組的值替換了目標數組中對應下標的值。

  • 取值函數的處理
    Object.assign只能進行值的復制,如果要復制的值是一個取值函數,那么將求值后再復制:
const source = {
  get foo() { return 1 }
};
const target = {};

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

常見用途

  • 為對象添加屬性
class Point {
  constructor(x, y) {
    Object.assign(this, {x, y});
  }
}
  • 為對象添加方法
Object.assign(SomeClass.prototype, {
  someMethod(arg1, arg2) {
    ···
  },
  anotherMethod() {
    ···
  }
});

// 等同于下面的寫法
SomeClass.prototype.someMethod = function (arg1, arg2) {
  ···
};
SomeClass.prototype.anotherMethod = function () {
  ···
};
  • 克隆對象
function clone(origin) {
  return Object.assign({}, origin);
}

上面代碼將原始對象拷貝到一個空對象,就得到了原始對象的克隆,但是只能克隆原始對象自身的值,不能克隆它繼承的值,下面的代碼可以實現克隆繼承的值:

function clone(origin) {
  let originProto = Object.getPrototypeOf(origin);
  return Object.assign(Object.create(originProto), origin);
}
  • 合并多個對象
const merge =
  (target, ...sources) => Object.assign(target, ...sources);

//合并后返回一個新對象
const merge =
  (...sources) => Object.assign({}, ...sources);
  • 為屬性指定默認值
const DEFAULTS = {
  logLevel: 0,
  outputFormat: 'html'
};

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

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.getOwnPropertyDescriptors()方法的引入就是為了解決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 }

上述代碼中,使用Object.assign拷貝source對象到target1對象,但是set方法并沒有被成功拷貝,其值變成了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)
);
  • 實現繼承
    老版本繼承對象:
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,
  })
);
  • 實現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__屬性

// es5 的寫法
const obj = {
  method: function() { ... }
};
obj.__proto__ = someOtherObj;

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

標準明確規定,只有瀏覽器必須部署這個屬性,其他運行環境不一定需要部署,而且新的代碼最好認為這個屬性是不存在的。因此,無論從語義的角度,還是從兼容性的角度,都不要使用這個屬性,而是使用下面的Object.setPrototypeOf()(寫操作)、Object.getPrototypeOf()(讀操作)、Object.create()(生成操作)代替。
具體實現上,__proto__調用的是Object.prototype.__proto__,具體實現如下:

Object.defineProperty(Object.prototype, '__proto__', {
  get() {
    let _thisObj = Object(this);
    return Object.getPrototypeOf(_thisObj);
  },
  set(proto) {
    if (this === undefined || this === null) {
      throw new TypeError();
    }
    if (!isObject(this)) {
      return undefined;
    }
    if (!isObject(proto)) {
      return undefined;
    }
    let status = Reflect.setPrototypeOf(this, proto);
    if (!status) {
      throw new TypeError();
    }
  },
});

function isObject(value) {
  return Object(value) === value;
}

Object.getPrototypeOf()

Object.getPrototypeOf()用于讀取一個對象的原型對象:

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.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

由于undefinednull無法轉為對象,所以如果第一個參數是undefinednull,就會報錯。

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

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

Object.keys()

返回一個成員是參數對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵名的數組:

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

Object.keys配套的Object.valuesObject.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默認是falseObject.values不會返回這個屬性。只要把enumerable改成trueObject.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(42) // []
Object.values(true) // []

Object.entries()

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

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

除了返回值不一樣,該方法的行為與Object.values基本一致。

Object.entries的基本用途是遍歷對象的屬性。

let obj = { one: 1, two: 2 };
for (let [k, v] of Object.entries(obj)) {
  console.log(
    `${JSON.stringify(k)}: ${JSON.stringify(v)}`
  );
}
// "one": 1
// "two": 2

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

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

自己實現Object.entries

// Generator函數的版本
function* entries(obj) {
  for (let key of Object.keys(obj)) {
    yield [key, obj[key]];
  }
}

// 非Generator函數的版本
function entries(obj) {
  let arr = [];
  for (let key of Object.keys(obj)) {
    arr.push([key, obj[key]]);
  }
  return arr;
}

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" }

參考

http://es6.ruanyifeng.com/#docs/object-methods#Object-is

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1.屬性的簡潔表示法 允許直接寫入變量和函數 上面代碼表明,ES6 允許在對象之中,直接寫變量。這時,屬性名為變量...
    雨飛飛雨閱讀 1,147評論 0 3
  • 屬性的簡潔表示法 ES6允許直接寫入變量和函數,作為對象的屬性和方法。 上面代碼表明,ES6允許在對象之中,直接寫...
    oWSQo閱讀 523評論 0 0
  • 屬性的簡潔表示法 ES6允許直接寫入變量和函數,作為對象的屬性和方法。這樣的書寫更加簡潔。 上面代碼表明,ES6允...
    呼呼哥閱讀 2,946評論 0 2
  • Object.freeze() 該方法可以凍結一個對象,凍結對象指的是不能向這個對象,添加屬性、刪除屬性、修改屬性...
    秦聲閱讀 3,696評論 0 10
  • “天地莊周馬,江湖范蠡船”是北京前大街的一個商鋪的對聯,橫批是億兆,橫批好理解,就是財源廣進的意思,對聯里包含了春...
    湡水俊卿閱讀 617評論 0 0