Skip to content

Instantly share code, notes, and snippets.

@mikesamuel
Created November 16, 2023 21:59
Show Gist options
  • Save mikesamuel/5817a9ff6365704dbd6db715cf62c168 to your computer and use it in GitHub Desktop.
Save mikesamuel/5817a9ff6365704dbd6db715cf62c168 to your computer and use it in GitHub Desktop.
Subjective method dispatch explanation
<!doctype html><meta charset=utf-8>
<!-- this file is subjectivity.html -->
<script>
// Just calls a method on the string it's given.
// Below each iframe locally overrides that method.
window.makeItBold = (str) => str.bold();
// We're loading the same HTML in three frames so fork.
switch (window.location.hash) {
case '': {
document.write(`
<!-- Set up two same origin frames -->
<iframe id="foo" src="./subjectivity.html#foo"></iframe>
<iframe id="bar" src="./subjectivity.html#bar"></iframe>
`);
// The string comes from the parent frame's realm, but passing it to a
// child Realm uses any overriden semantics for the method call.
let myString = "Hello, World!";
setTimeout(
() => {
console.log(`In parent: ${ window.makeItBold(myString) }`);
console.log(`In foo: ${ window.frames.foo.contentWindow.makeItBold(myString) }`);
console.log(`In bar: ${ window.frames.bar.contentWindow.makeItBold(myString) }`);
},
// HACK: give foo and bar time to load
1000 /* ms */,
);
break;
}
// Locally override the string method in child iframes
case '#foo': {
String.prototype.bold = function () {
return `<span class="bold">${this}</span>`;
};
break;
}
case '#bar': {
String.prototype.bold = function () { return `💪${this}` };
break;
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment