Object|Object defineProperty

可向对象添加属性或修改属性

Object.defineProperty(object, propertyname, descriptor)

value enumerable configurable writable
testDefineProperty() { var obj = { a: 'aaa', b: 'bbb' } Object.defineProperty(obj, 'noEnumerable', { value: 5,// 属性值 默认为undefined enumerable: false, // 是否可枚举 configurable: false, //能否使用delete、能否需改属性特性、或能否修改访问器属性 writable: false,//对象属性是否可修改 }) // test for in 可遍历原型对象的属性,不可遍历不可枚举属性 for (var key in obj) { console.log('for in:' + key) } // test Objec.keys() 智能遍历对象自身属性,不可遍历不可枚举属性 console.log(Object.keys(obj)) // test Object.getOwnPropertyNames ,可遍历不可枚举属性 console.log(Object.getOwnPropertyNames(obj)) // 可直接调用 console.log('noEnumerable:' + obj.noEnumerable) }

setter getter
testSetGet() { var obj = {} Object.defineProperty(obj, 'noEnumerable', { set: function (x) { this.newaccpropvalue = https://www.it610.com/article/x console.log('set noEnumerable') }, get: function () { console.log('get noEnumerable') return this.newaccpropvalue } } ) obj.noEnumerable = 1 console.log('noEnumerable:' + obj.noEnumerable) }

    推荐阅读