【问题标题】:new Function scope新功能范围
【发布时间】:2015-08-01 13:38:07
【问题描述】:

我有一段代码带有 ReferenceError here

或以下:

function foo() {

    function bar() {
        console.log('bar');
    }

    var x = new Function('bar();');
    x();
}

foo(); // ReferenceError: bar is not defined

有可能做到这一点吗?我的意思是 bar 函数存在于new Function

【问题讨论】:

  • 我不知道该接受哪个答案,所以几天后我会接受投票最多的答案。谢谢大家。

标签: javascript scope


【解决方案1】:

使用 Function 构造函数创建的函数不会为其创建上下文创建闭包;它们总是在全局范围内创建。运行它们时,它们将只能访问自己的局部变量和全局变量,而不是调用 Function 构造函数的范围内的变量。

——MDN

所以不,不是在使用这种方法时。

不要使用函数构造函数。效率低下,把字符串转成代码是fraught with problems

function foo() {

    function bar() {
        alert('bar');
    }

    function x() {
      bar();
    }
    x();
}

foo();

【讨论】:

  • 问题是 bar 由我定义/编码,但用户必须使用它。用户输入代码编辑器并执行。
  • 如果您必须采用这种方法,请使用eval
【解决方案2】:

一种可能的方法是使用eval 而不是new Function

function foo() {

    function bar() {
        console.log('bar');
    }

    eval('x = function() { bar(); }');
    x();
}

foo(); // works fine.

【讨论】:

  • 我试过了,但与我正在编码的文件中的“use strict”有冲突。当然,我可以删除严格模式,所以我认为这是唯一的方法。
  • 如果您不想要全局变量,您可能需要声明 x
  • 重点是在eval之后或new Function之后执行函数,以便用行号捕获错误。
猜你喜欢
  • 2015-09-25
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-04
  • 1970-01-01
相关资源
最近更新 更多