'Global getter javascript
In javascript, you can set object property getters like so
const obj = {
get a() {
return 1
}
}
console.log(obj.a) // 1
Is it possible to define a global getter? Something like:
let a = get() { return 1 }
console.log(a) // 1
Or, in the node REPL, obj shows up as: {a: [Getter]}
, so is there some sort of constructor I could use: let a = new Getter(() => {return 1})
Also, can I do the same with setters?
Solution 1:[1]
Since global variables are attached to the window
object, you can do so using Object.defineProperty()
:
Object.defineProperty(window, 'a', {
enumerable: true,
configurable: true,
get: function() {
console.log('you accessed "window.a"');
return this._a
},
set: function(val) {
this._a = val;
}
});
a = 10;
console.log(a);
Note that in Node.js, the global object is called global
, not window
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |