What's the correct prototype declaration so it catches all requests for varibles? With myObject being an object with the altered prototype.
That's not really related to JavaScript's prototypical inheritance. Creating objects with prototypes can either be done by using the new
keyword on constructor functions with their prototype
property, or via Object.create
. What you're interested in is how to construct an object where every property access…
would get caught by the function
This unfortunately not possible with current JavaScript. You can only set up properties (with values, or with getters/setters) with specific names, a catch-all behaviour is currently not implemented - though some few engines support the Proxy
draft. For that, see Is there an equivalent of the __noSuchMethod__ feature for properties, or a way to implement it in JS?, Javascript array with default values (equivalent of Python's defaultdict)? or Set undefined javascript property before read.
I think this comes closest to what you want - using an explicit getter function instead of properties:
function Entity() {
this.data = {position_X:5, foo:"bar", …};
}
Entity.prototype.get = function (name) {
console.log("access on "+name);
return this.data[name];
};
var entity = new Entity;
entity.get("x"); // undefined, but logs "access on x"
entity.get("position_X"); // 5, and logs "access on position_X"
entity.get("foo"); // "bar", and logs "access on foo"