×

找BUG:尝试查查ReferenceError: reference to undefined property "x"的缘由

作者:Terry2023.08.22来源:Web前端之家浏览:2856评论:0
关键词:js

今天突然遇到一个奇葩的问题,运行代码后,提示:ReferenceError: reference to undefined property "x"。我们可以一步步的去分析,往下看吧。

报错信息

ReferenceError: reference to undefined property "x" (Firefox)

错误类型

仅在 strict mode 下出现 ReferenceError 警告。

哪里出错了?

脚本尝试去访问一个不存在的对象属性。property accessors 页面描述了两种访问属性的方法。

引用未定义属性的错误仅出现在 strict mode 代码中。在非严格代码中,对不存在的属性的访问将被忽略。

示例

无效的

本例中,bar 属性是未定义的,隐藏 ReferenceError 会出现。

"use strict";

var foo = {};
foo.bar; // ReferenceError: reference to undefined property "bar"

正确演示

为了避免错误,您需要向对象添加 bar 的定义或在尝试访问 bar 属性之前检查 bar 属性的存在;一种检查的方式是使用 Object.prototype.hasOwnProperty() 方法。如下所示:

"use strict";

var foo = {};

// Define the bar property

foo.bar = "moon";
console.log(foo.bar); // "moon"

// Test to be sure bar exists before accessing it

if (foo.hasOwnProperty("bar") {
  console.log(foo.bar);
}

大家可以试试吧。

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/jsbug20230822a1.html

网友评论文明上网理性发言 已有0人参与

发表评论: