Javascript:函数已定义,但错误说..找不到函数! (奇怪) [英] Javascript: Function is defined, but Error says.. Function is not found ! (Strange)

查看:169
本文介绍了Javascript:函数已定义,但错误说..找不到函数! (奇怪)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

function mark()
{
    alert("This is a test box..");
}

setTimeout("mark()",5000);

错误:找不到功能标记()!!

Error : Function mark() is not found !!

还有其他一些问题..因为它适用于 http://jsfiddle.net/russcam/ 6EXa9 / 但它在我的应用程序中不起作用..你可以帮我调试吗?

There is some other issue.. as it works on http://jsfiddle.net/russcam/6EXa9/ but its not working in my application.. so can you help me debug this ?

还有什么可能是什么原因..顺便说一句我我在GreaseMonkey脚本中运行它!

What else can be the reason.. By the way I am running this inside a GreaseMonkey script !

推荐答案

如果您使用的是GreaseMonkey,您定义的任何函数都由GM沙箱化而不可用在主窗口中。

当您使用任何本机函数时,例如 setTimeout alert ,它们在main的上下文中调用窗口例如;
,当你打电话给 setTimeout 时,你实际上正在调用 window.setTimeout()

If you are using GreaseMonkey, any functions you define are sandboxed by GM and not available in the main window.
When you use any of the native functions however, like setTimeout or alert, they are called in the context of the main window e.g; when you call setTimeout you are actually calling window.setTimeout()

现在你定义的函数, mark 在主窗口中不存在,你要求 setTimeout 做的是评估字符串'mark()'。当超时触发
window.eval('mark()')被调用时,如上所述, window.mark 未定义。所以你有几个选择:

Now the function you have defined, mark doesn't exist in the main window and what you are asking setTimeout to do is evaluate the string 'mark()'. When the timeout fires window.eval( 'mark()' ) is called and as discussed, window.mark is not defined. So you have a couple of options:

1)在窗口对象上定义 mark 。 GM允许您通过 unsafeWindow 对象执行此操作:

1) Define mark on the window object. GM allows you to do this through the unsafeWindow object like this:

unsafeWindow.mark = function(){}
setTimeout( 'mark()', 10 );        //this works but is ugly, it uses eval

2)传递对本地标记到 setTimeout

function mark(){}
setTimeout( mark, 10 );        //this works too but you can't send parameters

但是如果你需要发送参数怎么办?
如果你在主窗口上定义了你的函数,eval方法就可以了(但是很难看 - 不要这样做)

But what if you need to send parameters? If you have defined your function on the main window, the eval method will work (but it is ugly - don't do it)

unsafeWindow.mark2 = function( param ) {
    alert( param )
}
setTimeout( 'mark2( "hello" )', 10 ); //this alerts hello

但是这个方法适用于带参数的函数,无论你是否在主窗口或仅在GM
中调用包含在匿名函数中并传递到 setTimeout

But this method will work for functions with parameters whether you have defined them on the main window or just in GM The call is wrapped in an anonymous function and passed into setTimeout

setTimeout( function() {
    mark2( "hello" )
}, 10 );                              //this alerts hello

这篇关于Javascript:函数已定义,但错误说..找不到函数! (奇怪)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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