静态方法:
1.Object.is()
ES5比较两个值是否相等只有两个运算符,==和===,它们都有各自的缺点,es6提供了Object.is来比较两个值是否相等
+0 === -0 //true
NaN === NaN // false
Object.is(+0, -0) // false
Object.is(NaN, NaN) // true
2.Object.assign
该方法用于对象的合并,将源(sourse)对象的所有可枚举的属性,复制到目标对象上
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拷贝的属性是有限制的,只拷贝源对象的自身属性(不拷贝继承属性),也不拷贝不可枚举的属性([[enumerable]]: false)。
注意点:
(1)Object.assign方法实行的是浅拷贝,而不是深拷贝。也就是说,如果源对象某个属性的值是对象,那么目标对象拷贝得到的是这个对象的引用。
(2)Object.assign可以用来处理数组,但是会把数组视为对象。
(3)Object.assign只能进行值的复制,如果要复制的值是一个取值函数,那么将求值后再复制。
常见用途:
(1)为对象添加属性
class Point {
constructor(x, y) {
Object.assign(this, {x, y});
}
}
(2)为对象添加方法
(3)克隆对象
function clone(origin) {
return Object.assign({}, origin);
}
上面代码只能克隆自身的属性,不能克隆继承的属性,若要克隆继承的属性,如下
function clone(origin) {
let originProto = Object.getPrototypeOf(origin);
return Object.assign(Object.create(originProto), origin);
}
(4)合并多个对象
const merge =
(target, ...sources) => Object.assign(target, ...sources);
如果希望合并后返回一个新对象,可以改写上面函数,对一个空对象合并。
const merge =
(...sources) => Object.assign({}, ...sources);
3.Object.getOwnPropertyDescriptors()
ES5的Object.getOwnPropertyDescriptor()方法返回某个对象的描述对象。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.assign()无法正确拷贝get属性和set属性的问题。
可以配合Object.create()方法,将对象属性克隆到一个新对象。这属于浅拷贝。
const clone = Object.create(Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj));
// 或者
const shallowClone = (obj) => Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
);
4.proto属性,Object.setPrototypeOf(),Object.getPrototypeOf
5.Object.keys(),Object.values(),Object.entries()
6.Object.fromEntries()
Object.fromEntries()方法是Object.entries()的逆操作,用于将一个键值对数组转为对象。
bject.fromEntries([
['foo', 'bar'],
['baz', 42]
])
// { foo: "bar", baz: 42 }
该方法的主要目的,是将键值对的数据结构还原为对象,因此特别适合将 Map 结构转为对象。