使用回调而不是字符串将代码封装在 javascript 中有什么优势?

What are the advantages of using callbacks over strings to encapsulate code in javascript?

在javascript中,可以将代码存储为字符串并使用'eval'执行它。另一方面,我们可以将代码表示为进一步执行的函数。为什么在 javascript 中使用闭包优于 'eval'?

编辑:

例如:

存储为字符串的代码:

function(x, y, callback){
  if (x > y){
      eval(callback);
  }
}

存储为函数的代码:

function(x, y, callback){
  if (x > y){
      callback();
  }
}

当您使用字符串时,您不会移除闭包。该函数仍然必须在相同的范围内,就像您直接调用该函数一样。通常你想避免使用 eval 因为它比较慢。例如:

function sayHi() {
    alert('hi');

    function sayHo() {
        alert('ho');
    }

    sayHo()
}

function callAnotherFunctionByString(func) {
    eval(func)
}

function callAnotherFunction(func) {
    func()
}

// Both of these will work
callAnotherFunctionByString('sayHi()');
callAnotherFunction(sayHi);

// Neither of these will work because the sayHo function is closed off to the sayHi function
callAnotherFunctionByString('sayHo()');
callAnotherFunction(sayHo);

eval本身不创建闭包,不提供封装。它只是一种评估 JavaScript 表示为字符串的代码的方法。

如果您使用 eval 来执行一个函数(就像您的示例所做的那样),它不会修改该函数的范围,也不会修改该函数创建的闭包。不管 eval,函数总是在它们最初声明的范围内执行,并且它们总是创建一个闭包(封装在该函数内所做的任何声明)。

范围和 eval 之间只有一处细微差别。如果您直接调用 eval 它将使用本地范围。如果您间接调用 eval,它将使用全局范围。

示例来自 MDN

function test() {
  var x = 2, y = 4;
  console.log(eval('x + y'));  // Direct call, uses local scope, result is 6
  var geval = eval; // equivalent to calling eval in the global scope
  console.log(geval('x + y')); // Indirect call, uses global scope, throws ReferenceError because `x` is undefined
}