在条件下重新加载 javascript 函数

Reload javascript function on condition

本文关键字:加载 javascript 函数 条件下 新加载      更新时间:2023-09-26

有没有办法在if条件下重新加载javascript函数?例如,假设我有一个函数

runCode(){
    //do something
}

首先我试过

setInterval(function(){
  runCode();
},1000);

但我不希望它在一段时间内重新加载,而是在 if 条件下。

假设我有一个函数,它有时会根据用户在文本区域中输入的内容返回 true,有时返回 false(例如!因此,在这种情况下,我希望能够在用户输入后检查它是否更改为 true 或 viceversa,如果它是真的,我需要重新加载函数runCode()

你试过吗?

if (expression) {
    runcode();
}

是的。您可以在 if 作用域内调用该函数。

if(condition){
runCode();
}

您可以使用 setter 在更改值后运行函数:

function sayHello(){
  alert('hello!');
}
Object.defineProperty(window, 'condVar', {
  get: function() {
    return this._condVar;
  },
  set: function(value) {
    if(value === 123)
      sayHello();
    this._condVar = value;
  }
});
alert('setting 123');
condVar = 123;
alert('setting abc');
condVar = 'abc';
alert('setting 123');
condVar = 123;

更多关于二传手:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set