Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Alert() Being Replaced

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?

like image 620
Ian Avatar asked Feb 22 '26 23:02

Ian


2 Answers

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;
})();
like image 145
Rob W Avatar answered Feb 25 '26 12:02

Rob W


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

like image 22
fflorent Avatar answered Feb 25 '26 12:02

fflorent