Look this code:
<script type = "text/javascript">
function mouseClick (container) {
container.appendChild (document.createTextNode ("Can you show me ? Try clicking anywhere."));
this.tryShowMe = "Yes man ! You can !"
window.addEventListener ("click", function (event) {
var ok = typeof this.tryShowMe === "undefined" ? "No, you can't." : this.tryShowMe;
alert (ok);
}, false);
}
window.addEventListener ("load", function () {
new mouseClick (document.body);
}, false);
</script>
The “this.tryShowMe” refers to the element “window”, instead, I want to refer to the object. Can I do that ?
Thanks
That’s a common pitfall in JavaScript.
You’re adding the event listener to
windowtherefore window is calling the function, which will result in thethisinside of the function being set towindow.thisnever references an outer scope in JavaScript, even if you call a plain function likefoo()inside another function, thethisinside offoowill default to the global object.If you want to access an outer
thisyou need to keep a reference to it:For an overview on the possible values and pitfalls of
this, take a look here.