Reputation: 148524
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 ?
Upvotes: 0
Views: 88
Reputation: 107508
EDIT: Zoiks, Lekensteyn hit the nail on the head. I didn't fully understand what you were intending to accomplish here...
That is not exactly a "self-executing function." If you had built it like this:
(function(MyObject) {
MyObject.alertMessage = "Javascript rules";
MyObject.ClickHandler = function() {
alert(this.alertMessage );
}
})(window.MyObject = window.MyObject || {});
Then I would call it a self-executing function.
Once you've done that, now you could execute MyObject.ClickHandler()
and get the alert.
Upvotes: 2
Reputation: 66405
You are missing the new
keyword. Currently, this
refers to window
and ClickHandler
is available through window.ClickHandler
.
When using the new
keyword, a new object is created and the this
keyword will refer to that newly created object. That is why the ClickHandler
method will be added to MyObject
below:
var MyObject = new (function () {
this.alertMessage = "Javascript rules";
this.ClickHandler = function () {
alert(this.alertMessage);
};
})();
Be careful when doing something like:
document.getElementById("MyButton")
.addEventListener("click", MyObject.ClickHandler, false);
addEventListener
makes this
refer to the object on which the event listener was assigned. See also bind
for changing the this
scope.
Upvotes: 3