[英]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 他们两个,即
noSuchValue
on object myString
, 对象myString
属性noSuchValue
, 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: 预期的行为是:
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.