ReferenceError: "x" is not defined
訊息
ReferenceError: "x" is not defined
錯誤類型
哪裡錯了?
實例
變數未宣告
js
foo.substring(1); // ReferenceError: foo is not defined
"foo" 變數在任何地方都沒被定義到。它需要字串使 String.prototype.substring()
得以運作。
js
var foo = "bar";
foo.substring(1); // "ar"
作用域錯誤
A variable need to be available in the current context of execution. Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function
js
function numbers() {
var num1 = 2,
num2 = 3;
return num1 + num2;
}
console.log(num1); // ReferenceError num1 is not defined.
However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope.
js
var num1 = 2,
num2 = 3;
function numbers() {
return num1 + num2;
}
console.log(num1); // 2