简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM