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?
thisinside the invoked anonymous function refers towindow. So, you’re overwriting the globalalertmethod.If you want to create a new object, with method
alert, use:An alternative method: