coderkearns
coderkearns

Reputation: 72

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?

Upvotes: 2

Views: 1042

Answers (1)

connexo
connexo

Reputation: 56753

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

Upvotes: 6

Related Questions