全球 getter javascript

Global getter javascript

在 javascript 中,您可以像这样设置对象 属性 getters

const obj = {
  get a() {
    return 1
  }
}

console.log(obj.a) // 1

是否可以定义一个全局getter?类似于:

let a = get() { return 1 }
console.log(a) // 1

或者,在节点 REPL 中,obj 显示为:{a: [Getter]},所以是否有某种我可以使用的构造函数:let a = new Getter(() => {return 1})

另外,我可以用 setter 做同样的事情吗?

由于 global 变量附加到 window 对象,您可以使用 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);

请注意 Node.js、the global object is called global,而不是 window