I have a need for the following functionality. I want to freeze the existing properties of an object, but allow for new properties to be added. For some reason, there seems to be no Object.freezeExisting() functionality, and I think it may be worthwhile to implement that, with the option of freezing existing properties of the prototype.
I have no idea how to do that. This is some code to get started, but this cannot be right at all. I don't care about performance that much, it just has to work 100%.
Object.freezeExistingProps = function(obj, modifyProto){
Object.keys(obj).forEach(function(key){
const val = obj[key];
Object.defineProperty(obj, key , { //we simply overwrite existing prop
value: val,
writable: false, // important, I think
enumerable: true,
configurable: false
});
});
return obj;
};
But I just need a sanity check on the above. I also need some info on how one could go down the prototype chain and somehow stop before messing with the actual Object.prototype.