简体   繁体   中英

Javascript Getters & Setters in body?

As far as I understand, getters & setters in javascript can only be used inside objects, such as:

const myObj = {
  a: 7,
  get b() {
    return this.a + 1;
  },
  set c(x) {
    this.a = x / 2;
  }
};

Which means that you access the getters & setters only via the object:

console.log(myObj.a);
console.log(myObj.b);
myObj.c = 50;
console.log(myObj.a);

Is there any way to also define getters & setters for variables in the body of the javascript code? Such as:

function set myVar(value)
{
    _myVar = value;
    (some other instructions...)
}

function get myVar()
{
    (some other instructions...)
    return _myVar;
}

myVar = 123;
console.log(myVar);

Yes you can, using Object.defineProperty . In browser javascript window is the global scope, adjust this to self (or globalThis ) in other contexts:

Object.defineProperty(window, 'a', {
    get: ()=>12,
    set: (v)=>console.log(v)
})

console.log(a);
a=12;

Object.defineProperty is how getters and setters are made, the syntax you use is just syntactic sugar for it.

Since we use globalThis this will only work in global scopes. Variables created this way are not deleted at the end of a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM