ReferenceError: "x" is not defined - JavaScript 编辑

The JavaScript exception "variable is not defined" occurs when there is a non-existent variable referenced somewhere.

Message

ReferenceError: "x" is not defined

Error type

ReferenceError.

What went wrong?

There is a non-existent variable referenced somewhere. This variable needs to be declared, or you need to make sure it is available in your current script or scope.

Note: When loading a library (such as jQuery), make sure it is loaded before you access library variables, such as "$". Put the <script> element that loads the library before your code that uses it.

Examples

Variable not declared

foo.substring(1); // ReferenceError: foo is not defined

The "foo" variable isn't defined anywhere. It needs to be some string, so that the String.prototype.substring() method will work.

var foo = 'bar';
foo.substring(1); // "ar"

Wrong scope

A variable needs 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

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.

var num1 = 2,
    num2 = 3;

function numbers() {
  return num1 + num2;
}

console.log(numbers()); // 5

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:87 次

字数:3283

最后编辑:7 年前

编辑次数:0 次

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文