简体   繁体   English

未被捕获的ReferenceError:您好未定义

[英]Uncaught ReferenceError: hello is not defined

Any idea why I have the error Uncaught ReferenceError: hello is not defined ? 知道为什么我有错误Uncaught ReferenceError:hello is not defined吗?

function hello() {
    console.log('hello ()');
    setTimeout("hello ()", 1000);
}
setTimeout("hello()", 1000);​

Here is a jsfiddle : http://jsfiddle.net/s9vLk/ 这是一个jsfiddle: http : //jsfiddle.net/s9vLk/

The JavaScript code in your demo runs within the 'load' event handler (the option "onLoad" is selected). 演示中的JavaScript代码在'load'事件处理程序中运行(已选择“ onLoad”选项)。 Therefore, the function hello is not a global function. 因此,函数hello不是全局函数。 You have to set the option to "no wrap (body)" or "no wrap (head)". 您必须将选项设置为“ no wrap(body)”或“ no wrap(head)”。 That way, your JavaScript code will be global code. 这样,您的JavaScript代码将成为全局代码。

Live demo: http://jsfiddle.net/s9vLk/1/ 现场演示: http //jsfiddle.net/s9vLk/1/

The problem is that you are passing strings to setTimeout() which means code in the string will effectively be eval ed and thus isn't running in the scope you think it's running in and so the hello() function isn't found. 问题是您要将字符串传递给setTimeout() ,这意味着将有效eval字符串中的代码,因此未在您认为它正在运行的范围内运行,因此找不到hello()函数。

If you change the jsfiddle options on the left from "onload" to "no wrap" it works as is because then the function will be global rather than nested inside the onload handler, but a better option is to pass a function reference to setTimeout() : 如果将左侧的jsfiddle选项从“ onload”更改为“ no wrap”,则按原样运行,因为该函数将是全局函数,而不是嵌套在onload处理函数中,但是更好的选择是将函数引用传递给setTimeout()

function hello() {
    console.log('hello ()');
    setTimeout(hello, 1000);
}
setTimeout(hello, 1000);

(Note: no parentheses after hello .) (注意: hello后没有括号。)

You have a space between hello and the () . hello()之间有一个空格。

You really should't pass the arguments as a string to setTimeout . 您确实不应该将参数作为字符串传递给setTimeout

You don't (and shouldn't) need to reference your function name as a string. 您不需要(也不应该)以字符串形式引用函数名。

function hello() {
    console.log('hello');
    setTimeout(hello, 1000);
}
setTimeout(hello, 1000);

Or better yet 还是更好

setInterval(function() {
    console.log('hello');
}, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM