Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 472
coderkearns Avatar asked Aug 01 '26 07:08

coderkearns


1 Answers

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.

Node.js

like image 86
connexo Avatar answered Aug 02 '26 21:08

connexo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!