【问题标题】:using "use strict" and variable scope使用“使用严格”和变量范围
【发布时间】:2012-05-07 02:02:27
【问题描述】:

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

(function(){
  "use strict";

  window.person = {}
  person.name = {
    first: "first name",
    last: this.first
  }
}());

似乎严格的 js 不再允许了。为什么要删除这个?有什么缺点吗?

【问题讨论】:

标签: javascript scope strict


【解决方案1】:

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

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

(function(){
    "use strict";

    window.person = {}
    person.name = {
        first: "first name",
        last: this.first
    }
}).call(this);

不管是严格/非严格模式,this 永远不会是对使用文字表示法创建的对象的引用。这就是 JavaScript 的工作原理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    相关资源
    最近更新 更多