如何在 javascript 中更改方法调用的全局范围

How to change global scope for a method call in javascript

本文关键字:调用 方法 全局 范围 javascript      更新时间:2024-04-28

我想从另一个 iframe 调用一个方法:

window.parent.frames[1].processInnerMessage(outerMessage)

但我希望它具有window.parent.frames[1]范围,而不是我当前的window,以便它将处理outerMessage,就好像它起源于该frame[1]本地一样。

- 这可能吗?谢谢。

window.parent.frames[1].processInnerMessage 已经被调用,范围为 window.parent.frames[1] ,无论您在哪里或如何调用它。函数的词法范围是在函数是和之后无法更改时创建的。

如果问题实际上是是否可以在 iframe 之间共享函数,以便函数实际上获得与调用方而不是被调用方相同的上下文,那么这会更有趣一些。

也就是说,如果我们有一个容器 html

<iframe src="frame0.html"></iframe>
<iframe src="frame1.html"></iframe>

frame1.html然后定义一个全局函数,如

function processInnerMessage(outerMessage){
    document.getElementById('message').innerHTML = outerMessage;
}

现在 frame0.html 想打印出它的消息

window.parent.frames[1].processInnerMessage('Hi there, neighbour!');

如上所述,这将导致消息被打印到 frame1.html 中的元素。但也许 frame0.html 也有 id 'message' 的元素,我们想在那里打印消息。

选项 1:在两个帧中分别定义函数

只需在两个 iframe 中分别加载包含此进程的脚本InnerMessage 函数,这样您就可以调用processInnerMessage()而无需任何frames[1]内容。这是显而易见的,老实说是最好的解决方案,几乎没有理由使用任何其他技巧。

选项 2:不要依赖全局范围

与其写document.getElementById('message'),不如写一些类似(this||window).document.getElementById('message')的东西,然后期望调用方用.processInnerMessage.call(window, 'Hi there, neighbour!')更改this的值

选项3:邪恶者

这是其中最黑客的解决方案,我不建议使用它,但它也是回答实际问题"[更改范围]可能吗?它本质上是通过使用 eval 重新创建函数来实现的。在第 0 帧中:

var processInnerMessage;
eval('processInnerMessage=' + window.parent.frames[1].processInnerMessage);
processInnerMessage('Hi there neighbour!');

丑陋,如果您在 frame0 中未定义的任何其他processInnerMessage函数,则会中断,但至少消息会打印在正确的框架中。