程序员的知识教程库

网站首页 > 教程分享 正文

我的JavaScript学习笔记:读取属性的特性

henian88 2024-08-17 16:06:13 教程分享 9 ℃ 0 评论

我们使用Object.getOwnPropertyDescription()获取给定属性的描述符。

语法:Object.getOwnPropertyDescription(obj,prop)

obj是属性所在的对象,prop是读取其描述符的属性名称。

let book = {};
        Object.defineProperties(book, {
            _year: { value: 2019 },
            edition: { value: 1 },
            year: {
                get: function () {
                    return this._year
                },
                set: function (newValue) {
                    if (newValue > 2019) {
                        this._year = newValue;
                        this.edition += newValue - 2019
                    }
                }
            }
        });
let descriptor=Object.getOwnPropertyDescriptor(book,"_year");
console.log(descriptor.value);//2019
console.log(typeof descriptor.get);//undefined
console.log(descriptor.configurable);//false
let descriptor=Object.getOwnPropertyDescriptor(book,"year");
console.log(descriptor.value);//undefined
console.log(descriptor.eunmerable);//false
console.log(typeof descriptor.get);//function

对于数据属性_year,value 等于最初的值,configurable 是 false,而 get 等于 undefined。 对于访问器属性 year,value 等于 undefined,enumerable 是 false,而 get 是一个指向 getter 函数的指针。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表