ℙℕℤℝ 2009-08-26 16:10
浏览 659
已采纳

在 JavaScript 中"使用严格"是做什么的,它背后的原因是什么?

Recently, I ran some of my JavaScript code through Crockford's JSLint, and it gave the following error:

Problem at line 1 character 1: Missing "use strict" statement.

Doing some searching, I realized that some people add "use strict"; into their JavaScript code. Once I added the statement, the error stopped appearing. Unfortunately, Google did not reveal much of the history behind this string statement. Certainly it must have something to do with how the JavaScript is interpreted by the browser, but I have no idea what the effect would be.

So what is "use strict"; all about, what does it imply, and is it still relevant?

Do any of the current browsers respond to the "use strict"; string or is it for future use?

转载于:https://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it

  • 写回答

25条回答 默认 最新

  • Didn"t forge 2009-08-26 16:15
    关注

    This article about Javascript Strict Mode might interest you: John Resig - ECMAScript 5 Strict Mode, JSON, and More

    To quote some interesting parts:

    Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.

    And:

    Strict mode helps out in a couple ways:

    • It catches some common coding bloopers, throwing exceptions.
    • It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
    • It disables features that are confusing or poorly thought out.

    Also note you can apply "strict mode" to the whole file... Or you can use it only for a specific function (still quoting from John Resig's article):

    // Non-strict code...
    
    (function(){
      "use strict";
    
      // Define your library strictly...
    })();
    
    // Non-strict code... 
    

    Which might be helpful if you have to mix old and new code ;-)

    So, I suppose it's a bit like the "use strict" you can use in Perl (hence the name?): it helps you make fewer errors, by detecting more things that could lead to breakages.

    Currently, it's supported by all major browsers (bar IE 9 and below).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(24条)

报告相同问题?

悬赏问题

  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢