今天突然遇到一个奇葩的问题,运行代码后,提示:ReferenceError: reference to undefined property "x"。我们可以一步步的去分析,往下看吧。
报错信息
ReferenceError: reference to undefined property "x" (Firefox)
仅在 strict mode 下出现 脚本尝试去访问一个不存在的对象属性。property accessors 页面描述了两种访问属性的方法。 引用未定义属性的错误仅出现在 strict mode 代码中。在非严格代码中,对不存在的属性的访问将被忽略。 本例中,错误类型
ReferenceError 警告。哪里出错了?
示例
无效的
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);
}大家可以试试吧。







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