I have the following javascript code:
<script type="text/javascript">
var x = 10;
window.onload = function() {
document.write(this.x); // <-- yields correct output: 10.
document.write(this.x); // <-- outputs "undefined"
document.write(this.x); // <-- outputs "undefined"
}
</script>
I am unable to understand why [this.x] results in undefined from the second time onwards. If I am correct, the function context (value of “this”), would refer to the global window object.
When you use
document.write()AFTER the document has loaded, it opens a new document (clearing the previous one). It appears that in some browsers (IE, for example), the global variables are immediately wiped out, even from the script that is still running that did thedocument.write(). The best answer here is to not usedocument.write()after the page has loaded. Instead, use DOM manipulation to change the existing document however you want it changed rather than creating a new document. You can see that things work fine (based on your more recent code example) if you use DOM manipulation (manipulating innerHTML) rather than usingdocument.write()in this jsFiddle.Since clearing the current document is almost never what you want to do, if you can explain what you’re really trying to accomplish we can help better with a solution.
If you want to
modifythe existing document after it has loaded, you need to use DOM manipulation functions such as.innerHTML(to change the HTML of a node) or DOM manipulation functions to add new nodes to the existing document, NOTdocument.write().You should generally not use
thisto refer to global variables. Global variables are available with no prefix (unless overriden locally) or available with thewindowprefix.So, either of these will work:
As to your question about using
this. The value ofthisis set one of several ways:pleasures.makeIceCream(), the value ofthiswill be set to thepleasuresobject in themakeIceCream()method.callmethod on function objects likemakeIceCream.call(pleasures), then the value ofthiswill be set to thepleasuresobject in this invocation of themakeIceCream()method.applymethod on function objects likemakeIceCream.apply(pleasures), then the value ofthiswill be set to thepleasuresobject in this invocation of themakeIceCream()method.You can read more about
.call()and.apply()in these MDN references:apply: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply
call: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call
At all other times, the value of
thisshould generally not be used as it has not been explicitly set. It is likely set to the global object (in a browser, this is thewindowobject) , but it is not considered best practice to use it to access global variables, nor is there any reason to.