【问题标题】:Uncaught Type Error: Cannot set property of undefined [duplicate]未捕获的类型错误:无法设置未定义的属性 [重复]
【发布时间】:2015-03-14 08:06:14
【问题描述】:

代码如下,很简单:

(function() {
  "use strict";

  // Define our constructor
  this.White = function() {
    this.version = "1.0.0";
  };
}());

// Later
a = new White();
alert(a.version);

JSBin 中(以及在运行JShint 时),它可以正常工作。 添加"use strict" 后在JSBin 中不起作用。但是,在 Chrome 中运行此脚本时,我会收到以下模糊消息:

未捕获的类型错误:无法设置未定义的属性“白色”

为什么?!

【问题讨论】:

  • 因为use strict thisundefined,否则它将是全局对象。
  • 您的代码期望 this 是对全局对象的引用。在您的代码中(在 jsbin 之外),如果外部范围处于“严格”模式,则 this 将是 undefined(因为这就是“严格”模式的工作方式)。
  • @elclanrs 谢谢,这确实有道理!所以我只需要window.White 而不是this.White 对吗?
  • 请注意,JSBin 似乎已在您发布的 sn-p 中没有 "use strict"; 的情况下保存。
  • @JonathanLonowski 我的错,感谢您指出这一点。将 'use strict'; 添加到 JSBin 也会破坏它.. 更新标题。

标签: javascript iife


【解决方案1】:

使用严格模式不会让你创建隐式全局变量。this.White 被全局提升并且它是隐式创建的。所以删除它会删除错误Strict Mode

【讨论】:

  • 如果你不想禁用严格模式,你可以简单地将this.White = ...替换为window.White = ...,用于基于浏览器的JS。
猜你喜欢
  • 1970-01-01
  • 2021-09-21
  • 2017-10-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
相关资源
最近更新 更多