gpt4 book ai didi

Javascript重新分配变量而不是中断引用

转载 作者:行者123 更新时间:2023-11-29 19:03:30 26 4
gpt4 key购买 nike

假设如下:

let __somevar__ = { hi: 'john' };
Object.defineProperty(window, 'somevar', {
set: (value)=>{
__somevar__ = value;
},
get: ()=>{
return __somevar__;
}
})

let newvar = window.somevar;

// Is it possible to keep the window.somevar reference so that is always uses the setters/getters?
// obviously this actually reassigns newvar instead of using the window.somevar setter.
newvar = { hi: 'senica' }

// These are different now.
console.log(newvar, window.somevar);

// Object.assign won't work because getters/setters are not enumerable.

// A proxy would work, but that's not my question.

不是特别重要...只是好奇。

谢谢!

最佳答案

就像我在评论中所说的那样,可以使用 Object.defineProperty 来完成,只是不能使用 =:

let __somevar__ = { hi: 'john' };
Object.defineProperty(window, 'somevar', {
set: (value)=>{
__somevar__ = value;
},
get: ()=>{
return __somevar__;
}
})

Object.defineProperty(window, 'newvar', Object.getOwnPropertyDescriptor(window, 'somevar'))

newvar = { hi: 'senica' }

console.log(newvar === window.somevar);

关于Javascript重新分配变量而不是中断引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44912787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com