Reputation: 11903
Let's say there's a function in the top window. For example:
function z() { alert(window.name); }
Let's also say there's an iframe in this document (same origin).
Can a function in the top window execute this function in the context of another window, such that it displays the name of the iframe and not the top window?
In other words, how is the global object bound to a function and can it be changed?
Naive attempt that doesn't work: https://jsfiddle.net/wos2o3gx/ (displays top for both invocations).
Upvotes: 15
Views: 2166
Reputation: 2077
you can use this
instead of window
in your example, like this:
function z() {
alert(this.name);
}
window.name = 'w top';
z();
var iframe = document.getElementById('iframe');
frame.contentWindow.name = 'w iframe';
frame.contentWindow.z = z;
frame.contentWindow.z();
Upvotes: 4
Reputation: 664307
how is the global object bound to a function?
By closure.
and can it be changed?
No. You'd need to create a new function, in the context of the other window (e.g. by using its eval
or Function
constructor).
Upvotes: 4
Reputation: 16779
How is the global object bound to a function and can it be changed?
A function's global context is determined at the time the function is created, and does not change even when you make that function a property of another window
context. There are dynamic alternatives, like substituting window
with this
, but since this
isn't always set to the global object (for example in strict mode), I would suggest passing a window
variable to your function instead:
function z (window) {
window = window || self
console.log(window.name)
}
window.name = 'w top'
z()
var iframe = document.getElementById('iframe')
iframe.contentWindow.name = 'w iframe'
z(iframe.contentWindow)
<iframe id="iframe" src="about:blank" name="w iframe">
</iframe>
Upvotes: 11