You have created a property of the prototype property which is non-configurable, but it can still be shadowed by properties of objects created by the constructor.
function ObjectNode() {
}
Object.defineProperty(ObjectNode.prototype, "parent", {
value: null,
configurable: false
})
ObjectNode.prototype.addChild = function (node) {
node.parent = this; // <-- node.parent is now enumerable
}
var mom = new ObjectNode();
var kid = new ObjectNode();
mom.addChild(kid);
console.log(kid.parent == mom); // works, logs true
kid.parent = "foo";
console.log(kid.parent); // works, logs "foo"
ObjectNode.prototype.parent = "foo";
console.log(ObjectNode.prototype.parent); // fails, logs null
The thing to remember is that properties of an object are properties of that object only, not properties of other objects with that object in their prototype chain. Instead, try creating a non-configurable property of the new object in the constructor:
function ObjectNode() {
Object.defineProperty(this, "parent", {
value: null,
configurable: false
})
}
Of course, this will prevent your addChild
function from working, since the property is no longer configurable. You could consider defining the property in that function instead, but it will still be configurable until it is set with addChild
.
All in all, your best bet in general is to not worry about making things unconfigurable if it's not absolutely critical (and I'm not sure of any case where it would be). The world has gotten along pretty well without that functionality for a long time. ;)