There is any interesting article which warns about JS problems.
However, notice #2:
<input type="button" value="Gotcha!" id="MyButton" >
<script>
var MyObject = function () {
this.alertMessage = "Javascript rules";
this.ClickHandler = function() {
alert(this.alertMessage );
}
}();
</script>
Notice the self executing function by () at the end. However I’m pretty sure the this.xxx is used when doing new MyObject(). He wrote :
If you call
MyObject.ClickHandler();you will get a popup saying “Javascript rules”.
and his sample doesn’t work. I’ve tried MyObject.ClickHandler() and got an error…(Cannot call method ‘ClickHandler’ of undefined)
How can I make MyObject.ClickHandler() work ?
You are missing the
newkeyword. Currently,thisrefers towindowandClickHandleris available throughwindow.ClickHandler.When using the
newkeyword, a new object is created and thethiskeyword will refer to that newly created object. That is why theClickHandlermethod will be added toMyObjectbelow:Be careful when doing something like:
addEventListenermakesthisrefer to the object on which the event listener was assigned. See alsobindfor changing thethisscope.