Skip to content

Instantly share code, notes, and snippets.

@DigiTec
Last active August 29, 2015 14:21
Show Gist options
  • Save DigiTec/69213bfb15fa659f3762 to your computer and use it in GitHub Desktop.
Save DigiTec/69213bfb15fa659f3762 to your computer and use it in GitHub Desktop.
Browser Lexical Scope Functions created using inline event handlers.

Some additional JSFiddle links that I produced afterwards to experiment with timing around when the browser would create its scope chains. It turns out browsers don't tend to create scope chains until the first time the event is fired.

In this example we have a button in a form. We can check its scope first, then change it, then check it again to see one behavior. We can then change scope and execute it to see a different behavior. http://jsfiddle.net/oko08kaw/

This example switches us from one form to another, which is a slightly more complicated behavior but achieves similar results. http://jsfiddle.net/p7bu92jw/2/

<!-- http://jsfiddle.net/2rkkhyqz/ -->
<button
id="simple"
onclick="console.log(singleWindow); console.log(singleEmbed); console.log(multiplyNamed); console.log(window['multiplyNamed']);"
>Click Me!</button>
<iframe name="singleWindow" src="about:blank"></iframe>
<embed name="singleEmbed"></embed>
<iframe name="multiplyNamed" src="about:blank"></iframe>
<embed name="multiplyNamed"></embed>
<script>
var simpleButton = document.getElementById("simple");
simpleButton.addEventListener("click", function () {
console.log(multiplyNamed);
});
</script>
<!-- http://jsfiddle.net/5tqgrow4/3/ -->
<form id="theWrapper" onsubmit="return false;">
<button id="theClicker"
onclick="console.log('my this', this); console.log('element scope', interestingProperty); console.log('form scope', formProp); console.log('document scope', docProp); console.log('form collection', length); foo();"
>Normal Button</button></form>
<button
form="theWrapper"
onclick="console.log('out of form parent', formProp);"
>Out of Band Button</button>
<form id="theWrapper2">
<button
form="theWrapper"
onclick="console.log('other form parent', formProp);"
>Other Form Button</button>
</form>
<!-- http://jsfiddle.net/vtsvjeu0/1/ -->
<button id="simple" onclick="console.log(this); console.log(variable1, 'in button'); callout();">Click Me!</button>
<script>
var simpleButton = document.getElementById("simple");
window.variable1 = "global foo";
window.variable2 = "global bar";
simpleButton.variable1 = "foo";
simpleButton.variable2 = "bar";
function callout() {
console.log(variable1, "callout");
}
</script>
// http://jsfiddle.net/fuqd47ju/
var simpleButton = document.getElementById("simple");
window.variable1 = "global foo";
window.variable2 = "global bar";
simpleButton.variable1 = "foo";
simpleButton.variable2 = "bar";
simpleButton.onclick = function () {
console.log(this);
console.log(variable1);
console.log(this.variable1);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment