问题描述
let foo = {};
我正在将它重新分配给其他东西。
foo = {}
问题是我怎么知道变量被重新赋值了?
就像我听说过代理一样,但它不起作用
// Creating a variable
let foo = {}
// Setting up a proxy
const fooProxy = new Proxy(foo,_ => {
get: function(...) { ... },set: function(...) { ... }
}
// I just re-assigned the variable,and I want that `notify()` to tell me about it.
foo = {}
// I wanna call this function when the variable changes,but it doesn't work
function notify(){
console.log("Dude,your variable has changed!");
解决方法
有几个例子,但我想这归结为目的?如果手段是为了保护变量不被改变,那可能不会发生,但你可以通过回调和承诺/等来接近。
class User {
constructor(name) {
this.name = name;
this.skill = "novice";
}
setSkill(newSkill) {
this.skill = newSkill;
this.alertChange()
}
alertChange(){
console.log(this.name+ " OH NO,My Skill!!!! No SECURITY HERE I GUESS?");
}
}
let Test = new User("Donny");
Test.setSkill("Egg Champion");
let test = undefined;
let test2 = undefined;
let watchvalue = 0;
function RepeatTillReady() {
clearTimeout(test);
clearTimeout(test2);
test = setTimeout(()=>{
if (watchvalue == 100) {
console.log("That took a while but we made it!");
} else {
RepeatTillReady();
}
},200);
test2 = setTimeout(()=>{
watchvalue++;
console.log("counting slowly now"+watchvalue);
},100);
}
RepeatTillReady();
这是尝试在浏览器中捕获 DOM 负载时的另一个有趣示例! :)