【问题标题】:Possible to enable "strict mode" in FireBug and Chrome's console?可以在 FireBug 和 Chrome 的控制台中启用“严格模式”吗?
【发布时间】:2012-07-26 20:24:23
【问题描述】:

有了这个页面:

<!DOCTYPE html>
<html>
  <head>
    <script>
        "use strict";
        var foo = 2;
        delete foo;
    </script>
  </head>
  <body></body>
</html>

Firebug 控制台给出:

applying the 'delete' operator to an unqualified name is deprecated
>>> foo
ReferenceError: foo is not defined
foo

但是这样就成功了:

>>> var bar = 2;
undefined
>>> delete bar;
true

即使您注释掉delete foo; 以便脚本不会中断,删除bar 仍然是成功的,尽管它“是一个全局对象的属性,因为它是通过变量声明创建的,@987654321 也是如此@":

>>> foo
2
>>> delete foo
false
>>> var bar = 2;
undefined
>>> delete bar
true

是否可以在 FireBug 和/或 Chrome 的控制台中启用“严格模式”?

【问题讨论】:

  • 我想知道控制台代码是否正在通过eval() 进行管道传输,在这种情况下不会设置 DontDelete 属性。
  • ...好吧,如果我刚刚阅读了下一节:And this is the gist of Firebug’s abnormal behavior. All the text in console seems to be parsed and executed as Eval code, not as a Global or Function one.
  • 我遵循了@zoranc 的第一个建议,这样我就可以看到严格模式在 chrome 的控制台中工作。 (function f() { 'use strict'; console.log('"this" here is: ', this, 'Strict Mode is cool...'); } ());(function f() { console.log('"this" here is: ', this, 'Global variables are evil! So Crockford told me...'); } ());
  • devtools 控制台应该有一个复选框来为所有命令启用严格模式

标签: javascript console strict-mode


【解决方案1】:

firebug 控制台通过将所有代码包装在“eval”调用中来工作,因此脚本中的第一条语句不再是“use strict” - 因此它被禁用。您可以尝试将代码包装在一个函数中以对该特定函数强制“使用严格”,但我所知道的最佳解决方案是跳过控制台并直接在页面本身中进行测试。

【讨论】:

    【解决方案2】:

    使用 shift+enter 输入 'use strict'

    像这样

    【讨论】:

    • 它有效。只需要确保添加“使用严格”;在 F12 Chrome 控制台中的每次交互。
    【解决方案3】:

    如果你只是在控制台中测试一个函数,你也可以把'use strict'作为函数声明的第一行。

    【讨论】:

      【解决方案4】:

      Chrome:在代码行中添加 'use strict'; 前缀(和/或 shift+enter 表示多行)

      'use strict'; var foo = 2; delete foo;

      【讨论】:

        【解决方案5】:

        在 Chrome 上,转到“chrome://flags”,然后“启用实验性 JavaScript”。重新启动。

        【讨论】:

        • 这是不正确的。该标志允许使用最新的 ES 功能。
        猜你喜欢
        • 1970-01-01
        • 2012-10-14
        • 2014-08-13
        • 2011-10-26
        • 2011-08-25
        • 2015-11-01
        • 2011-05-21
        • 2019-04-16
        • 2012-01-17
        相关资源
        最近更新 更多