微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 JavaScript 中处理变量赋值

如何解决如何在 JavaScript 中处理变量赋值

假设我有一个变量

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 负载时的另一个有趣示例! :)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。