据我所知,javascript中的getter&setter只能在对象中使用,例如:
const myObj = {
a: 7,
get b() {
return this.a + 1;
},
set c(x) {
this.a = x / 2;
}
};这意味着您只能通过对象访问getter和setter:
console.log(myObj.a);
console.log(myObj.b);
myObj.c = 50;
console.log(myObj.a);有没有任何方法也为javascript代码正文中的变量定义getters和setter?例如:
function set myVar(value)
{
_myVar = value;
(some other instructions...)
}
function get myVar()
{
(some other instructions...)
return _myVar;
}
myVar = 123;
console.log(myVar);发布于 2022-09-14 09:43:29
是的,你可以使用Object.defineProperty。在浏览器javascript window中,将其调整为self (或globalThis)在其他上下文中:
Object.defineProperty(window, 'a', {
get: ()=>12,
set: (v)=>console.log(v)
})
console.log(a);
a=12;Object.defineProperty是如何生成getter和setter的,您使用的语法只是它的语法糖。
因为我们使用globalThis,所以这只会在全局范围内起作用。以这种方式创建的变量不会在函数的末尾删除。
https://stackoverflow.com/questions/73714658
复制相似问题