简体   繁体   English

在JS中更改全局范围

[英]Changing the global scope in JS

Say i have an Iframe running inside of a parent window. 假设我有一个Iframe在父窗口中运行。

I have a single script loaded inside the Iframe and I want that script to have access to the variables inside of its parent. 我在Iframe加载了一个脚本,并且希望该脚本可以访问其父级内部的变量。

Rather than saying window.parent.X all the time, is it possible to just declare: 不必一直说window.parent.X ,而是可以声明:

window= window.parent;

inside of the Iframe ? Iframe内部?

window is a protected variable for js, you will not be able to override it. window是js的受保护变量,您将无法覆盖它。 You can, however, store window.parent in another var and then use that: 但是,您可以将window.parent存储在另一个window.parent中,然后使用该window.parent

var parentWindow = window.parent;

can you give an example of what you mean by "create a closure that shadows it" 你能举一个“创建一个封闭它的阴影”的意思的例子吗?

// `window` here works normally

(function (window) {
    // `window` here is what would be `window.parent`
}(window.parent));

// `window` here works normally

Please note that even inside the IIFE 's closure you still have the same global object, ie anything you don't access via window will not be from the parent window. 请注意,即使在IIFE的闭包内部,您仍然具有相同的全局对象,即,您不通过window访问的任何内容都不会来自父窗口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM