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
noSuchValue
on object myString
, 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:
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.