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?