Every property has a 'descriptor'. If you were to introduce this code below, you will see this...
var foo = {x:20};
var des = Object.getOwnPropertyDescriptor(foo,'x');
console.log('foo.x - descriptor =',des);
The descriptor for foo.x
looks like this:
Object {
value : 20,
writable : true,
enumerable : true,
configurable : true
}
As you can see configurable
,enumerable
and writable
have already been pre-set to true
, so there is no need to do this in defineProperty
.
Also... If the descriptor has either get
or set
it CAN'T have either value
or writable
, and vice-versa, as this will cause an error like this:
Object.defineProperty(foo,'y',{
value : 5,
get : function(){return 10}
});
Will give the error:
Uncaught TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute.
"accessors" being get
& set
.
I understand that you are trying to get/set the value of foo.x
, but you have not defined anything to value
yet. Something like, but NOT:
Object.defineProperty(foo, "x", {
var value = this;
All-in-all you are going about this the wrong way. Take a look at this code and see if it helps:
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