I'm confused as to why the global alert() function is being replaced when I run this code... I'm not using prototype here.
Moo = (function(){
this.alert = function(s){
console.log("Replaced Alert! " + s);
};
return this;
})();
alert("poit");
When I run the code I do not get an alert popup, instead it runs the above code and I see the text appear in my console. Can someone explain?
this inside the invoked anonymous function refers to window. So, you're overwriting the global alert method.
If you want to create a new object, with method alert, use:
Moo = (function(){
var obj = {};
obj.alert = function(s){
console.log("Replaced Alert! " + s);
};
return obj;
})();
An alternative method:
Moo = (function(){
var obj = new function(){};
obj.prototype.alert = function(){...}
return new obj;
})();
As said above, the problem is that in your case, this refers to window (since you are not in a constructor).
Didn't you want to do that instead ? :
Moo = new (function(){
this.alert = function(s){
console.log("Replaced Alert! " + s);
};
return this;
})();
with the new keyword
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With