2011-12-29 51 views
0

在正常的JS,一个可以遍历window对象 -迭代的“窗口”全局

<html><head><script> 
function one(){ 
} 
function two(){ 
    for (var i in window) { 
    if (i=='one') { 
     alert(i);//.......................shows 'one' 
    } 
    } 
} 
two(); 
</script></head></html> 

但在Greasemonkey的的“窗口”不保持功能,即使你在通用脚本定义的函数:

// ==UserScript== 
// @name   Page 3 
// @namespace  http://xxxxxxxxxxxxxxxx 
// @include  http://xxxxxxxxx.net/3.html 
// ==/UserScript== 
// 
function one(){ 
} 
function two(){ 
    for (var i in window) { 
    if (i=='one') { 
     alert(i);//.........shows nothing, only iterates native window props 
    } 
    } 
} 
two(); 

是的,我想迭代我自己的函数,而不是unsafeWindow中的函数。请注意,以下的作品,我不想做的事:

window.one=function one(){ 
} 
function two(){ 
    for (var i in window) { 
    if (i=='one') { 
     alert(i);//...........ta-da! 'one' 
    } 
    } 
} 
two(); 

那么,什么是这个全球性空间的名字,我怎么重复它,究竟是什么异常的意图和最佳做法?谢谢。

更新:“这个”不访问功能或者 -

// ==UserScript== 
// @name   Page 3 
// @namespace  http://xxxxxxx.net 
// @include  http://xxxx.com/* 
// ==/UserScript== 


function do_fixes(){ 
    var s=''; 
    for (var i in this) { 
    if (i=='do_fixes') { 
     alert('yes'); 
    } 
    } 
    if (window!=this) { 
    alert('window!=this'); 
    } 
} 

do_fixes(); 
alert('this script ran!'); 

回答

1

全局对象应在全球范围内免费功能this访问。从上Greasemonkey Environment的Greasemonkey的手册页:

除非@Unwrap元当务之急是存在于用户的脚本标头,整个脚本被包裹的匿名函数内部,为保证脚本的标识符不与现有标识符碰撞在Mozilla JavaScript沙箱中。此函数包装函数将所有函数定义和var变量声明(例如var i = 5;)捕获到函数的本地作用域中。但是,在没有var的情况下发出的声明最终会在脚本的this对象上完成,该对象在Greasemonkey中是全局对象,与普通的浏览器对象模型相反,window对象填充此函数。

皱纹是,你需要unwrap脚本为您的功能被添加到脚本全球(注意全局变量通过this是访问,无需展开)。请注意,@unwrap建议只用于调试,因为如果变量和函数具有相同的名称,它们将与沙箱变量和函数发生冲突。

另一种方法是创建您自己的对象来代替全局对象的使用方法:

var global = {}; 

global.one = function() {...}; 
global.two = function (target) { 
    for (p in global) { 
     if (p == target) { 
      GM_log("found " +target); 
     } 
    } 
}; 
two('one'); 

虽然你可以明确地添加用作该脚本全局方法,那会给你最糟糕的两个世界:与沙箱属性冲突,并且不是自动的。

+0

感谢您的回复,但“此”不包含这些功能 - 我已更新我的帖子以显示该功能。 – 2011-12-29 17:19:54