0

I would like to set the property x when I first initialise my object, and then call Object.defineProperty. If I try to first access foo.x the console tells me that "value is not defined".

var foo = {x:20};

Object.defineProperty(foo, "x", {
    writeable: true,
    enumerable: true,
    configurable: true,
    get: function(){ 
      console.log("Get X value");
      return value;
     },
    set: function(newValue){
      console.log("Set X value");
      value = newValue;
    }
});
console.log(foo.x);  // **Uncaught ReferenceError: value is not defined** 
foo.x = 1;
console.log(foo.x);
foo.x = 10;
console.log(foo.x);
4

1 回答 1

0

每个属性都有一个“描述符”。如果您要在下面介绍此代码,您将看到...

var foo = {x:20};

var des = Object.getOwnPropertyDescriptor(foo,'x');
console.log('foo.x - descriptor =',des);

的描述符foo.x如下所示:

Object {
    value        : 20,
    writable     : true,
    enumerable   : true,
    configurable : true
}

如您所见configurableenumerable并且writable已经预先设置为true,因此无需在defineProperty.


另外...如果描述符有getset它不能有valuewritable,反之亦然,因为这将导致如下错误:

Object.defineProperty(foo,'y',{
    value   : 5,
    get     : function(){return 10}
});

会报错:

Uncaught TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute.

“访问者”是get& set


我了解您正在尝试获取/设置 的值foo.x,但您尚未定义任何内容value。类似但不是:

Object.defineProperty(foo, "x", {
    var value = this;

总而言之,你正在以错误的方式解决这个问题。看看这段代码,看看它是否有帮助:

var foo = {x:20};

Object.defineProperty(foo,'y',{
    get : function(){
        console.log('Get foo.x');
        return this.x;
    },
    set : function(val){
        console.log('Set foo.x');
        this.x = val;
    }
});

console.log(foo.x);     //  20
console.log(foo.y);     //  get foo.x (20)
foo.y = 10;             //  set foo.x to 10
console.log(foo.x);     //  10
console.log(foo.y);     //  10
于 2016-07-02T10:03:48.497 回答