Ian
Ian

Reputation: 25346

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?

Upvotes: 2

Views: 164

Answers (3)

fflorent
fflorent

Reputation: 1656

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

Upvotes: 3

Dave Newton
Dave Newton

Reputation: 160251

The this is evaluated as the global context (window).

The semantics of this in JavaScript are not always what you'd expect.

Upvotes: 0

Rob W
Rob W

Reputation: 349102

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;
})();

Upvotes: 8

Related Questions