Reputation: 45
On mozilla website they say:
// Example where we create an object with a couple of sample properties.
// (Note that the second parameter maps keys to *property descriptors*.)
o = Object.create(Object.prototype, {
// foo is a regular 'value property'
foo: { writable: true, configurable: true, value: 'hello' },
// bar is a getter-and-setter (accessor) property
bar: {
configurable: false,
get: function() { return 10; },
set: function(value) { console.log('Setting `o.bar` to', value); }
/* with ES5 Accessors our code can look like this
get function() { return 10; },
set function(value) { console.log('setting `o.bar` to', value); } */
}
});
But when I run this code, I can call o.bar but but do I call the set method?
o.bar calls the get, but what do I do to call the set?
Here's the code set up with a fiddle LINK
Upvotes: 1
Views: 34
Reputation: 50797
If you want to deal with the issues raised by @CyberneticTwerkGuruOrc, you can write it like this, storing the actual value in an internal closure variable:
o = Object.create(Object.prototype, {
foo: { writable: true, configurable: true, value: 'hello' },
bar: (function() {
var internalValue = 10;
return {
configurable: false,
get: function() { return internalValue; },
set: function(value) {
console.log('Setting `bar` to', value);
internalValue = value;
}
};
}())
});
o.bar; //=> 10
o.bar = 12; // logs 'Setting `bar` to 12'.
o.bar; //> 12
Upvotes: 1
Reputation: 543
Simply set the o.bar
like this to call the 'set' function:
o.bar = 3
Setting `o.bar` to 3
3
EDIT:
As @CyberneticTwerkGuruOrc mentions in the comments, the setter does not set anything in this case. To do so you have to use the input value
and actually set some (other) value, ex: this.foo = value
Upvotes: 3