I would like JS to throw an error when a object is used that isn't properly instantiated.
I have tried like this already:
var person = function () { throw new Error('Person not instantiated!'); };
...
var x = person.age; //should throw an error when person isn't overwritten
but it doesn't throw an error like I want it (only if I would type person();).
The problem here is that I give the object into numerious methods and don't want to make error handling for all occurrences. Is there a way to throw an error when reading a property of an object?
Is there a way to throw an error when reading a property of an object?
Yes you can patch the property getter with a function throwing an error
var person = {};
Object.defineProperty(person, 'age', {
get: function () { throw new Error('Person not instantiated!') },
});
var x = person.age;
Or you can also replace the object with a Proxy that will allow you to override a getter for all properties:
var person = new Proxy({}, {
get(target, name) {
throw new Error('Person not instantiated!');
}
});
var x = person.age;
var y = person.name;
But all of this is an anti-pattern. Is something that I would suggest against.