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).
What is an Execution Context? Simply put, an execution context is an abstract concept of an environment where the Javascript code is evaluated and executed. Whenever any code is run in JavaScript, it's run inside an execution context.
The Execution Context contains the code that's currently running, and everything that aids in its execution. During the Execution Context run-time, the specific code gets parsed by a parser, the variables and functions are stored in memory, executable byte-code gets generated, and the code gets executed.
The Execution Context is an abstract environment created by JS to execute code. The Execution Stack is used to execute functions and keep track of all the Execution Context created. The Execution context is created in two stages, the creation and the execution stage.
The code inside a function is executed when the function is invoked. It is common to use the term "call a function" instead of "invoke a function". It is also common to say "call upon a function", "start a function", or "execute a function".
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With