简体   繁体   English

Java中未捕获的引用错误和未定义

[英]Uncaught Reference Error in Javascript & undefined

Consider: 考虑:

var myString = new String("Hello world");
alert(myString.noSuchValue); // undefined

alert(myshit);  // This results in error, and not the above one

Both of them, ie 他们两个,即

  • property noSuchValue on object myString , 对象myString属性noSuchValue
  • variable myshit 可变的myshit

are undefined . 没有定义

But why do I get an error for myshit and not for the object property case ? 但是,为什么我会因myshit而不是对象属性的情况出错

在此处输入图片说明

Consider a slight modification of your code: 考虑对您的代码进行一些修改:

var myString = "Hello world";
var noSuchValue = myString.noSuchValue;
alert(noSuchValue);

In this example, noSuchValue is a defined variable with the value undefined . 在此示例中, noSuchValue是值为undefined定义变量

Contrast this to: 与此相比:

alert(otherValue);

Here, otherValue is an undefined variable (ie a value that has not been declared with var ), with no value whatsoever. 在这里, otherValue是一个未定义的变量 (即尚未使用var声明的值),没有任何值。

JavaScript can handle variables with values equal to undefined just fine, but it throws an exception when it sees an undefined variable. JavaScript可以很好地处理值等于undefined变量,但是当看到未定义的变量时,它将引发异常。

You can obtain the proper answer from the ECMAScript specs , but I'll summarize it in the following example: 您可以从ECMAScript规范中获得正确的答案,但在以下示例中将对其进行总结:

var data= myObj.prop1;

The expected behavior is: 预期的行为是:

  • if myObj (the base reference) does not exist, throw a ReferenceError. 如果myObj(基本引用)不存在,则引发ReferenceError。
  • if the base exists, but the property not, return undefined 如果基存在,但属性不存在,则返回undefined

It's probably because you can refer to a non-existent member to assign it on an existing object, eg 可能是因为您可以引用不存在的成员将其分配给现有对象,例如

var myObject = {firstMember: "test1"};
myObject.secondMember = "test2";

It makes sense for the value on the left hand side of the assignment to be a meaningful expression. 赋值左侧的值是有意义的表达是有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM