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

查看:82
本文介绍了是什么导致“功能未定义”将字符串传递给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);

它工作正常,但是firebug显示错误:

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.

哪个更正确?为什么firebug会出现这样的错误?

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天全站免登陆