对象的新增方法

ES新增对象方法

1、Object.is()
2、Object.assign()
3、Object.getOwnPropertyDescriptors()
4、proto Object.setPrototypeOf() Object.getPrototypeOf()
5、Object.keys() Object.values() Object.entries()

Object.is() 判断是否同值相等 值相等就是相等的,类似于===
Object.is(11, 11) // true
Object.is(NaN, NaN) // true
Object.is(+0, -0) // false
Object.is(1, '1') // false
Object.is({}, {}) // false

// 实现方式
Object.defineProperty(Object, 'is', {
  value: function(x, y) {
    if (x === y) {
      // 针对+0 和 -0 返回false
      return x !== 0 || 1 / x === 1 / y
    }
    // 针对NaN时返回true
    return x !== x && y !== y
  },
  configurable: true,
  enumerable: false,
  writable: true
})
Object.assign() 对象合并,可枚举属性 合并
let target = {a: 1, b: 2}
let obj1 = {b: 3, c: 4}
let obj2 = {d: 5}
Object.assign(target, obj1, obj2)
Object.assign(obj2) === obj2 // true 只有一个参数时会返回它自己
typeof Object.assign(2) // object 非对象会转换为对象,但是null 和undefined会报错

// ES2017 Object.getOwnPropertyDescriptors() 返回对象所有自身属性的描述对象
const obj3 = {
  aa: 3,
  getCar: () => {return 123}
}
Object.getOwnPropertyDescriptors(obj3)

// 实现方式
function getOwnPropertyDescriptors(obj) {
  const result = {}
  for (let key of Reflect.ownKeys(obj)) {
    result[key] = Object.getOwnPropertyDescriptor(obj, key)
  }
  return result
}
proto Object.setPrototypeOf() Object.getPrototypeOf()
const obj4 = {
  a: 1,
  b: 2
}
const proto = {}

Object.setPrototypeOf(obj4, proto)
proto.c = 3
proto.d = 4

console.log(obj4.d) // 由于proto是obj4的原型对象,所以obj4可以访问proto的属性
Object.getPrototypeOf(obj4) // 读取对象的原型对象
Object.keys() Object.values() Object.entries() Object.fromEntries()
const obj5 = {
  o1: 111,
  o2: 222,
  o3: 333,
  getOdd: () => {
    return this.o1
  }
}

const arr1 = [{o1: 111}, {o2: 222}]

Object.keys(obj5)
Object.values(obj5)
Object.entries(obj5) // 将对象转换为数组
Object.fromEntries(arr1) // 数组转对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值