更改 JS 中的全局范围
Changing the global scope in JS
假设我有一个 Iframe
运行 在父 window 里面。
我在 Iframe
中加载了一个脚本,我希望该脚本能够访问其父脚本中的变量。
而不是一直说 window.parent.X
,是否可以只声明:
window= window.parent;
在 Iframe
?
里面
window
是js的保护变量,你将无法覆盖它。但是,您可以将 window.parent
存储在另一个 var 中,然后使用它:
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
请注意,即使在 IIFE 的闭包中,您仍然拥有相同的全局 object,即您无法通过 window
访问的任何内容不会来自 parent window.
假设我有一个 Iframe
运行 在父 window 里面。
我在 Iframe
中加载了一个脚本,我希望该脚本能够访问其父脚本中的变量。
而不是一直说 window.parent.X
,是否可以只声明:
window= window.parent;
在 Iframe
?
window
是js的保护变量,你将无法覆盖它。但是,您可以将 window.parent
存储在另一个 var 中,然后使用它:
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
请注意,即使在 IIFE 的闭包中,您仍然拥有相同的全局 object,即您无法通过 window
访问的任何内容不会来自 parent window.