// abc was never declared.if (abc) {// ReferenceError: abc is not defined}
另一种情况是变量已经定义,但有一个getter函数,在调用时会抛出错误。例如,
// or it's a property that can throw an errorObject.defineProperty(window, "myVariable", {get: function() { throw new Error("W00t?"); },set: undefined});if (myVariable) {// Error: W00t?}
undefined = 2;
(function (undefined) {console.log(undefined); // prints out undefined// and for comparison:if (undeclaredvar === undefined) console.log("it works!")})()
var myVariableToCheck = 'myVar';if (window[myVariableToCheck] === undefined)console.log("Not declared or declared, but undefined.");
// Or you can check it directlyif (window['myVar'] === undefined)console.log("Not declared or declared, but undefined.");
var x;if (x === undefined) {alert ("I am declared, but not defined.")};if (typeof y === "undefined") {alert ("I am not even declared.")};
/* One more thing to understand: typeof ==='undefined' also checksfor if a variable is declared, but no value is assigned. In otherwords, the variable is declared, but not defined. */
// Will repeat above logic of x for typeof === 'undefined'if (x === undefined) {alert ("I am declared, but not defined.")};/* So typeof === 'undefined' works for both, but x === undefinedonly works for a variable which is at least declared. */
/* Say if I try using typeof === undefined (not in quotes) fora variable which is not even declared, we will get run atime error. */
if (z === undefined) {alert ("I am neither declared nor defined.")};// I got this error for z ReferenceError: z is not defined
// x has not been defined beforeif (typeof x === 'undefined') { // Evaluates to true without errors.// These statements execute.}
if (x === undefined) { // Throws a ReferenceError
}