最近,我通过克罗福德 查了一些JavaScript代码JSLint JSLint,并给出了以下错误:

第1行第1字符1:缺少“严格使用”声明的问题。

在做一些搜索时,我意识到有些人加了"use strict";输入 JavaScript 代码。 一旦我添加了该语句, 错误就不再出现。 不幸的是, Google 并未披露此字符串语句背后的大部分历史。 当然, 它肯定与浏览器如何解读 JavaScript 有关, 但我不知道效果会是什么 。

那么,什么是"use strict";关于它的意义是什么,它是否仍然相关?

当前浏览器中的任意浏览器响应"use strict";字符串, 还是用于未来用途 ?


当前回答

如果人们担心使用use strict也许值得看看这篇文章:

在浏览器中支持 ECMAScript 5 “ 立体模式” 。 这是什么意思 ?
NovoGeeek.com - 克里希纳的博客

讨论浏览器支持, 但更重要的是如何安全处理:

function isStrictMode(){
    return !this;
} 
/*
   returns false, since 'this' refers to global object and 
   '!this' becomes false
*/

function isStrictMode(){   
    "use strict";
    return !this;
} 
/* 
   returns true, since in strict mode the keyword 'this'
   does not refer to global object, unlike traditional JS. 
   So here, 'this' is 'undefined' and '!this' becomes true.
*/

其他回答

开发者应该使用的主要理由"use strict"它们是:

  1. 防止意外宣布全球变量。"use strict()"将会确保变量被声明为var在使用之前使用。 如 :

    function useStrictDemo(){
     'use strict';
     //works fine
     var a = 'No Problem';
    
     //does not work fine and throws error
     k = "problem"
    
     //even this will throw error
     someObject = {'problem': 'lot of problem'};
    }
    
  2. 注:N.B:"use strict"指令仅在脚本或函数的开头确认。
  3. 字符串"arguments"无法用作变量 :

    "use strict";
    var arguments = 3.14;    // This will cause an error
    
  4. 将限制关键字作为变量的使用。 试图使用关键字将会丢弃错误 。

简言之,你的代码将减少容易出错的程度,反过来又将使得你写好代码。

更多信息,请查看在这里.

如果人们担心使用use strict也许值得看看这篇文章:

在浏览器中支持 ECMAScript 5 “ 立体模式” 。 这是什么意思 ?
NovoGeeek.com - 克里希纳的博客

讨论浏览器支持, 但更重要的是如何安全处理:

function isStrictMode(){
    return !this;
} 
/*
   returns false, since 'this' refers to global object and 
   '!this' becomes false
*/

function isStrictMode(){   
    "use strict";
    return !this;
} 
/* 
   returns true, since in strict mode the keyword 'this'
   does not refer to global object, unlike traditional JS. 
   So here, 'this' is 'undefined' and '!this' becomes true.
*/

这是ECMAScript 5. 约翰·瑞西格写的新特写精美的摘要来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来,来

您在 JavaScript 文件( 文件顶部或函数内部) 中插入的字符串, 看起来像 :

"use strict";

在您的代码中输入它不会对当前浏览器造成任何问题, 因为它只是一条字符串。 如果您的代码违反 pragma , 它可能会在未来对您的代码造成问题 。 例如, 如果您有foo = "bar"未定义foo首先,你的代码将开始失败... 这在我看来是件好事

严格模式允许在 v8 引擎中设置严格的特性。 某些特性的短示例 :

您可通过写作方式在全球范围启用它 :

'use strict'; // strict mode enabled!

您只是在函数中包含的每个函数 :

let myfunc = () => {
  'use strict'; // strict mode enabled
  
   b = 0; // broke
}
  • 在使用该变量( sane imo) 之前, 您必须声明变量 :
  var x;
  x = '0'; // ok
  y = '';  // not ok
  • 已经启用 es6 功能( 取决于浏览器) , 因为节点 v4+ 很重要 。

  • 在某些情况下,业绩更好。

还有更多的特征,检查在这里更多! 更多! 更多! 更多! 更多!

use strict这是一种让您的代码更安全的方法, 因为您不能使用危险特性, 这些特性不能像你预期的那样工作。 而且,正如以前所写的那样, 它使代码更加严格。