未定义angularjs和window.x中的“使用严格”,但仍运行文件而没有错误

时间:2018-07-06 18:31:59

标签: javascript angularjs

我正在尝试编写AngularJS和JavaScript函数,但是我对关键字'use strict'有疑问。假设代码如下所示,保存在script标记内的html文件中。现在请记住,我们正在使用'use strict'关键字。 window.x并没有在html中定义。当我在Google Chrome浏览器中加载HTML文件时,为什么不抱怨window.x?它不是未定义的吗?输出为window.x: undefined。因此,AngularJS是否不应该检测未定义的任何变量并将其作为Google Chrome控制台中的错误喷出? Chrome为什么不抱怨未定义的变量?

(
  function() {
    'use strict';
    var x = "hello";

    console.log("window.x:", window.x); //undefined
    console.log("x:", x); //hello
    angular.module('myFirstApp', [])
      .controller('MyFirstController', function() {

      });
  })();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

1 个答案:

答案 0 :(得分:1)

'use strict'不检查属性是否存在/访问(window.x试图在x上查找属性window)-这样做的代价太高了。相反,它可以确保声明变量。