可以启用“严格模式";在 FireBug 和 Chrome 的控制台中?

2022-01-11 00:00:00 console javascript strict-mode

有了这个页面:

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

Firebug 控制台给出:

Firebug console gives:

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 仍然是成功的,尽管它是全局对象的属性"因为它是通过变量声明创建的,所以 DontDelete 属性":

Even if you comment out delete foo; so that the script does not break, deleting bar is still successful despite the fact it "is a property of a Global object as it is created via variable declaration and so has DontDelete attribute":

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

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

Is it possible to enable "strict mode" in FireBug and or Chrome's console?

推荐答案

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

The firebug console works by wrapping all the code in an "eval" call so the first statement in your script is no longer "use strict" - hence it is disabled. You could try wrapping your code in a function to enforce "use strict" for that particular function but the best solution I know of is to skip the console and test straight in the page itself.

相关文章