是什么导致“功能未定义"?将字符串传递给setTimeout时? [英] What causes "function is not defined" when passing a string to setTimeout?

查看:45
本文介绍了是什么导致“功能未定义"?将字符串传递给setTimeout时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var my_new_function = function(){
----
};
window.setTimeout(my_new_function, 1600);

以上内容正常运行,没有任何错误.

the above works properly without any errors.

当我使用时:

window.setTimeout("my_new_function()", 1600);

它工作正常,但是萤火虫显示错误:

it's working properly, but firebug is showing error :

my_new_function未定义

my_new_function is not defined

在一些有关setTimeout的文章中,我发现像第一种方法那样调用函数,而在另一些文章中,我看到了另一种方法.

in some articles about setTimeout, i found calling functions like in the 1st method, and in some other articles, i saw the other method.

哪个更正确?为什么萤火虫会显示这样的错误?

which is more correct? and why is firebug showing such an error?

推荐答案

使用

window.setTimeout(my_new_function, 1600);

您正在设置对该功能的引用.

You are setting the reference to the function.

第二个setTimeout示例中的函数

The function in your second setTimeout example

window.setTimeout("my_new_function()", 1600);

在执行时需要评估.评估时,它将在全局范围内执行.因此,如果该功能在本地范围内,则浏览器将找不到它.[听起来像是您的问题]

needs to be evaluated when it is executed. When it is evaluated it is being executed in global scope. So if the function is in local scope the browser will not find it. [Sounds like this is your issue]

经验丰富的开发人员不建议在setTimeout中使用字符串,因为每次都需要对其进行评估.这意味着执行需要更长的时间.

Seasoned developers will not recommend using strings in setTimeout since they need to be evaluated each time. All that means is it takes longer to execute.

另一个调用setTimeout的选项是

Another option to call setTimeout is

window.setTimeout( function(){ my_new_function(); }, 1600);

这篇关于是什么导致“功能未定义"?将字符串传递给setTimeout时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆