简体   繁体   中英

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 ,
  • variable myshit

are undefined .

But why do I get an error for myshit and not for the object property case ?

在此处输入图片说明

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 .

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.

JavaScript can handle variables with values equal to undefined just fine, but it throws an exception when it sees an undefined variable.

You can obtain the proper answer from the ECMAScript specs , but I'll summarize it in the following example:

var data= myObj.prop1;

The expected behavior is:

  • if myObj (the base reference) does not exist, throw a ReferenceError.
  • if the base exists, but the property not, return 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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