14

JavaScript has getters with Object.defineProperty. So I can define a getter on the property random of window by

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 object property? I am looking to do something like

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

window.Function // Prints "Accessing property Function of window."

Can I do "universal getters" in JavaScript?

Randomblue
  • 112,777
  • 145
  • 353
  • 547
  • possible duplicate of [Is it possible to implement dynamic getters/setters in JavaScript?](http://stackoverflow.com/questions/7891937/is-it-possible-to-implement-dynamic-getters-setters-in-javascript) – user123444555621 Feb 13 '13 at 20:24
  • 1
    Also see http://stackoverflow.com/questions/2266789/is-there-an-equivalent-of-the-nosuchmethod-feature-for-properties-or-a-way – user123444555621 Feb 13 '13 at 20:27

2 Answers2

17

Unfortunately: No, there isn't.

There is somehthing called Proxy Objects Introduced in Gecko 18 based Browsers

Which would allow you to do things like this

(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 this is not Standard and still very unstable

Btw I originally thought you could directly use window as local variable in the IIFE but it seems you can't it just logs undefined (wondering why) so I capitalized the "W"

Heres an example on JSBin

Note: You should visit it in Firefox

Community
  • 1
  • 1
Moritz Roessler
  • 8,542
  • 26
  • 51
  • 6
    [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) is now standard and being implemented as part of ES2015 – CletusW Aug 31 '16 at 19:11
9

No.

It is not possible to do in ECMAScript 5th edition as there is no provision for this operation. While such is not explicit stated, it can be seen that [GetProperty] does not make any provisions for non-existing properties.

The getters/setters in ECMAScript require existing properties and there is no equivalent of Ruby's method_missing or Python's __getattribute__.