JSLint错误:语句位置出现意外表达式'use strict'

4
当我尝试在Sublime Text中保存以下代码时,
'use strict';
 /*global angular,_*/

 var app = angular.module("myApp", []);
 app.controller("myCtrl", function ($scope) {
   $scope.firstName = "John";
   $scope.lastName = "Doe";
 });

我正在遇到以下JSLint错误:
 #1 Unexpected expression 'use strict' in statement position.
    'use strict'; // Line 1, Pos 1
 #2 Place the '/*global*/' directive before the first statement.
    /*global angular,_*/ // Line 2, Pos 1
 #3 Undeclared 'angular'.
    var app = angular.module("myApp", []); // Line 4, Pos 11
 #4 Expected 'use strict' before '$scope'.
    $scope.firstName = "John"; // Line 6, Pos 3
 #5 Expected '$scope' at column 5, not column 3.
    $scope.lastName = "Doe"; // Line 7, Pos 3

我已经检查了@TheSharpieOne提供的链接,但它并不能满足我的需求。 - Ayan
所以...答案的一部分说:“根据文档 ,JSLint的浏览器选项会自动禁用全局级别的"use strict"。据我所知,没有办法重新启用它。”这并没有帮助你意识到你不能在那里放置'use strict';,而把它放在那里才是问题的原因吗? - TheSharpieOne
如果没有使用'use strict',那么 JSLint 会报错:"在 '$scope' 前面期望 'use strict'"。 - Ayan
1个回答

3
您不能在全局范围内使用'use strict';,并且jslint也不支持此功能。请参见https://dev59.com/lpPfa4cB1Zd3GeqPJecc#35297691 因此,您需要将其从全局作用域中删除,并在函数作用域中添加它,或者将所有内容包装在IFEE中。
 /*global angular,_*/
 var app = angular.module("myApp", []);
 app.controller("myCtrl", function ($scope) {
  'use strict';
   $scope.firstName = "John";
   $scope.lastName = "Doe";
 });

或者将其包装:

/*global angular,_*/
(function(){
  'use strict';
   var app = angular.module("myApp", []);
   app.controller("myCtrl", function ($scope) {
     $scope.firstName = "John";
     $scope.lastName = "Doe";
   });
})();

1
是的,但不完全是。JSLint会将函数字面量用括号包裹视为错误,并给出以下错误信息:“不要在函数字面量周围加上括号。” - schlenger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接