全局 getter javascript

cod*_*rns 2 javascript getter getter-setter

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

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

console.log(obj.a) // 1
Run Code Online (Sandbox Code Playgroud)

是否可以定义一个全局getter?就像是:

let a = get() { return 1 }
console.log(a) // 1
Run Code Online (Sandbox Code Playgroud)

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

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

con*_*exo 6

由于全局变量附加到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);
Run Code Online (Sandbox Code Playgroud)

请注意,在 Node.js 中,全局对象称为global,而不是window

Node.js