在javaScript对象字面量中定义访问器属性

来源:互联网 发布:淘宝网红模特有哪些 编辑:程序博客网 时间:2024/05/29 04:47

我们知道,要给对象定义访问器属性,需要使用 Object.defineProperty()方法。

这个方法只能在对象字面量定义以外来使用。形如:

var testObj={_x:10,_y:20};Object.defineProperty(testObj,"X",{propDescriptor});

那么,是否可以在对象字面量中直接定义访问器属性呢?
我能想到的办法就是通过函数。
当然,这种方法最后还需要在外部调用一次函数才能真正的定义出访问器属性。

var testObj = {    _x: 12,    _y: 15,    acsY: function accessorY(propNameY) {        if (this.hasOwnProperty(propNameY)) return;        Object.defineProperty(this, propNameY, {            enumerable:true,            get: function readY() {                return _y;            },            set: function setY(yValue) {                _y = yValue;            }        })    },    acsX: function accessorX(propNameX) {        if (this.hasOwnProperty(propNameX)) return;        Object.defineProperty(this, propNameX, {            enumerable:true,            get: function readX() {                return _x;            },            set: function setX(xValue) {                _x = xValue;            }        })    }};testObj.acsX("X");testObj.acsY("Y");for (var propName in testObj) {    console.log(propName)}

需要注意的点是:
必须在描述符对象中指定 enumerable:true,否则 for in 循环找不到这个属性。

原创粉丝点击