The only way I know how to do that is to make the variable non-private, but two examples, the second more terse:
(function testInheritance(global, doc) {
"use strict";
var MyFunc = Object.create({}, {
_foo: {
value: "Some Default Value",
writable: true,
enumerable: true
},
foo: {
get: function() {
return this._foo;
},
set: function(value) {
this._foo = value;
}
}
}),
testFunc = Object.create(MyFunc);
console.log(testFunc.foo); // "Some default value"
testFunc.foo = "boo";
console.log(testFunc.foo); // "boo";
testFunc._foo = "Not a private variable anymore";
console.log(testFunc.foo); // "Not a private variable anymore"
}(window, document));
(function testInheritanceTwo(global, doc) {
"use strict";
var MyFunc = Object.create({}, {
foo: {
get: function() {
if (!this._foo) {
return "Some default value set by the getter.";
}
return this._foo;
},
set: function(value) {
this._foo = value;
}
}
}),
testFunc = Object.create(MyFunc);
console.log(testFunc.foo); // "Some default value set by the getter."
testFunc.foo = "Whomp";
console.log(testFunc.foo); // "Whomp";
testFunc._foo = "Not a private variable anymore, unfortunately.";
console.log(testFunc.foo); // "Not a private variable anymore"
}(window, document));
So far as I can tell:
You can't reference the value with the same name as what you use in set: function(value) or you end up with an infinite loop where setting the value calls the set value and it calls itself again, and so forth. Hence, your problem.
If you try to make the variable _foo to private, then the setter does not work. With this syntax it seems you can hide the variable, but you cannot really make it private.