美文网首页
js getOwnPropertyDescriptor()

js getOwnPropertyDescriptor()

作者: small_zeo | 来源:发表于2021-04-12 15:37 被阅读0次

定义

Object.getOwnPropertyDescriptor() 方法返回指定对象上一个自有属性对应的属性描述符。(自有属性指的是直接赋予该对象的属性,不需要从原型链上进行查找的属性)

语法

Object.getOwnPropertyDescriptor(obj, prop)

参数

obj: 需要查找的目标对象
prop: 目标对象内属性名称

返回值

如果指定的属性存在于对象上,则返回其属性描述符对象(property descriptor),否则返回undefined。

示例

       //定义一个空的对象
        const object1 = { }

        //结合Object.defineProperty方法来定义属性名
        Object.defineProperty(object1, "name", {
            value: "Zeo",
            configurable: false,
            writable: true
        })


        const descriptor = Object.getOwnPropertyDescriptor(object1, "name")
        console.log('descriptor =====', descriptor)
        /*  output
          {
            configurable: false
            enumerable: false
            value: "Zeo"
            writable: true
          }
        */
        descriptor.writable = false;
        for(var prop in descriptor){
            console.log('prop=====', prop)
        }
        /* output
        prop===== value
        prop===== writable
        prop===== enumerable
        prop===== configurable
        */

浏览器兼容性

image.png

相关文章

网友评论

      本文标题:js getOwnPropertyDescriptor()

      本文链接:https://www.haomeiwen.com/subject/ydsxlltx.html