首页 > 技术文章 > JavaScript | 数据属性与访问器属性

hughdong 2017-07-31 12:45 原文

属性类型

数据属性 - 包含一个数据值的位置,可以读取和写入值

[writable]

是否能修改属性的值

true

[enumerable]

是否通过for in 循环返回属性(是否可以被枚举)

true

[configurable]

是否能通过delete删除,能否修改属性的特性,能否修改访问器属性

true

[value]

包含这个属性的数据值,读取属性值的时候从这个位置读取。

undefined

访问器属性

[enumerable]

是否通过for in 循环返回属性(是否可以被枚举)

true

[configurable]

是否能通过delete删除,能否修改属性的特性,能否修改访问器属性

true

[get]

读取属性时调用的函数

undefined

[set]

写入属性时调用的函数

undefined

属性操作

  • 定义属性:Object.defineProperty()
  • 查看属性:Object.getOwnPropertyDescriptor()
"use strict";
// *****************************************************************
// 操作数据属性
var person = {
    name: 'hugh',
    age: 29,
    sayName: function() { console.log(1); }
}
// 修改属性默认特性:Object.defineProperty()
Object.defineProperty(person, "name", {
    writable: true,
    value: 'dong',
    configurable: false,
    enumerable: false
});
console.log(person);

// *****************************************************************
// 操作访问器属性
var book = {
    _year: 2004, // _作为标记只能通过对象访问的属性
    edition: 0
};
Object.defineProperty(book, "year", {
    // 访问器属性year包含setter和getter函数
    get: function() {
        return this._year;
    },
    set: function(newValue) {
        this._year = newValue;
        this.edition = newValue - 2004;
    }
})
book.year = 2008;
console.log(book);
console.log(book.edition);
// 旧方法,ie8部分不支持defineProperty()
// 严格模式不可用
// book._defineGetter_("year",function(){
//     return this._year;
// });
// book._defineSetter_("year",function(newValue){
//     this._year = newValue;
//     this.edition = newValue - 2014;
// });

// *****************************************************************
// 定义多个属性
var book2 = {};
Object.defineProperties(book2, {
    // 数据属性
    _year: {
        value: 2004,
        writable: false,
        enumerable: false,
        configurable: true
    },
    edition: {
        value: 0,
        writable: false,
        enumerable: false,
        configurable: true
    },
    // 访问器属性
    year: {
        get: function() {
            return this._year;
        },
        set: function(newValue) {
            this._year = newValue;
            this.edition = newValue - 3000;
        }
    }
});
console.log(book2);

// *****************************************************************
// 查看属性的属性
console.log(Object.getOwnPropertyDescriptor(book2,'_year'));
console.log(Object.getOwnPropertyDescriptor(book2,'edition'));
console.log(Object.getOwnPropertyDescriptor(book2,'year'));

推荐阅读