JS ES6 Object 对象属性的扩展
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 技术交流群。
上一篇: JS ES6 函数的拓展
下一篇: TypeScript 常见问题
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论