Let’s say I have some random code like below:
<script>
this.fn = (function() {
var element = document.createElement("div");
element.innerHTML = Object.keys(self) +
"<br />" + Object.keys(window) +
"<br />" + Object.keys(top);
self["document"].body.appendChild(element);
return arguments.callee;
})();
</script>
Not only having to do with the above code, what’s the difference between:
Self, Document, This, Top, Window?
What’s a best use case for each?
self&window: They both reference the current window (or frame) where the script is located and running. See here for details and examples.document: References the DOM container, giving you access to the headers and the body contents. See here for details and examples.this: References the JavaScript object under which the code is executed. JavaScript code and functions written directly inside<script>tags havethisrefer towindow. If an object’s function needs to call a method in the same object, usethis.method_name();.top: References the top-mostwindowobject in a frame hierarchy. If you use frames and want to manipulate the whole frameset window from inside a sub-frame, usetop, e.g.top.close();to close the current window containing all the frames.