JS ES6 Object 对象属性的扩展

发布于 2025-01-12 00:06:35 字数 2130 浏览 6 评论 0

Object.getOwnPropertyDescriptors()

ES5:Object.getOwnPropertyDescriptor(obj, prop) 方法会返回某个对象属性的描述对象 ES6:Object.getOwnPropertyDescriptors(obj) 返回指定对象所有自身属性(非继承属性)的描述对象。

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

__proto__ 属性

用来读取或设置当前对象的 prototype 对象

//实现上,__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
}

由于只有浏览器部署了该属性,故 ES6 推荐

  • Object.setPrototypeOf()(写操作)
  • Object.getPrototypeOf()(读操作)
  • Object.create()(生成操作)

Object.setPrototypeOf()

设置一个对象的 prototype 对象,返回的是第一个参数

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

Object.getPrototypeOf()

读取一个对象的原型对象

Object.getPrototypeOf(1) === Number.prototype // true
Object.getPrototypeOf('foo') === String.prototype // true
Object.getPrototypeOf(true) === Boolean.prototype // true
Object.getPrototypeOf(null)
// TypeError: Cannot convert undefined or null to object
Object.getPrototypeOf(undefined)
// TypeError: Cannot convert undefined or null to object

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

做个ˇ局外人

暂无简介

文章
评论
25 人气
更多

推荐作者

迷鸟归林

文章 0 评论 0

alipaysp_h2Vbo4sv6k

文章 0 评论 0

清风无影

文章 0 评论 0

mnbvcxz

文章 0 评论 0

听不够的曲调

文章 0 评论 0

秋叶绚丽

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文