使用"use strict"和变量范围

Moo*_*oon 2 javascript scope strict

我最近开始使用"use strict"我的脚本.我注意到的一个行为就是这个.[name of variable]不适用于对象.例如:

(function(){
  "use strict";

  window.person = {}
  person.name = {
    first: "first name",
    last: this.first
  }
}());
Run Code Online (Sandbox Code Playgroud)

似乎严格的js不再允许它.为什么要删除?有什么缺点吗?

cli*_*ity 8

在没有任何隐式或显式上下文设置的情况下调用的函数中,this变为undefined.

如果您立即调用的函数的外部上下文是全局范围,并且这是您对其自身上下文的预期,则可以使用.call(this)它将其上下文设置为外部上下文的上下文.

(function(){
    "use strict";

    window.person = {}
    person.name = {
        first: "first name",
        last: this.first
    }
}).call(this);
Run Code Online (Sandbox Code Playgroud)

无论严格/非严格模式如何,this永远不会使用文字符号来引用正在创建的对象.这就是JavaScript的工作原理.