Universal / Fallback getter property definition in JavaScript

JavaScript has recipients with Object.defineProperty . Therefore, I can define getter on the random of window property on

 Object.defineProperty(window, 'random', { get: function () { return Math.random(); } }); random // Evaluates to a random number 

Is it possible to define a "universal getter" for a given object, regardless of the property of the object? I want to do something like

 Object.universalGetter(window, function (propertyName) { console.log('Accessing property', propertyName, 'of window.'); }); window.Function // Prints "Accessing property Function of window." 

Is it possible to do "universal getters" in JavaScript?

+8
javascript getter
source share
2 answers

Not.

In ECMAScript 5th edition this cannot be done because there are no provisions for this operation. Although this is not explicitly stated, you can see that [GetProperty] does not contain any provisions for non-existent properties.

Recipients / setters in ECMAScript require existing properties and there is no equivalent to Ruby method_missing or Python __getattribute__ .

+4
source share

Unfortunately: No, it does not exist.

There is something called Proxy Objects presented in the Gecko 18 browser

What will allow you to do such things

 (function (original, Window) { var handler = { get: function (target, propertyName) { console.log('Accessing property', propertyName, 'of window.'); return target[propertyName]; } }; Window = new Proxy(original, handler); console.log(Window.setTimeout); // "Accessing property" // "setTimeout" // "of window." // function setTimeout() { // [native code] // } })(window); 

But it is not standard and still very unstable

Btw I initially thought you could use window directly as a local variable in IIFE, but it seems you can't just log in undefined (I wonder why), so I capitalized the letters "W"

Here is an example on JSBin

Note. You must visit it in Firefox.

+10
source share

All Articles