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

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

问题描述

这是我的代码:

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

setTimeout("mark()",5000);

错误:找不到功能mark()!

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 )时,它们会在主窗口的上下文中调用,例如: 当您呼叫 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 :

2) Pass a reference to the local mark to 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

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

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