Ian*_*Ian 2 javascript alert object this
我很困惑为什么在alert()
运行这段代码时全局函数被替换...我不是prototype
在这里使用.
Moo = (function(){
this.alert = function(s){
console.log("Replaced Alert! " + s);
};
return this;
})();
alert("poit");
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,我没有得到警告弹出窗口,而是运行上面的代码,我看到文本出现在我的控制台中.谁能解释一下?
this
在调用的匿名函数里面引用window
.所以,你要覆盖全局alert
方法.
如果要使用方法创建新对象alert
,请使用:
Moo = (function(){
var obj = {};
obj.alert = function(s){
console.log("Replaced Alert! " + s);
};
return obj;
})();
Run Code Online (Sandbox Code Playgroud)
另一种方法:
Moo = (function(){
var obj = new function(){};
obj.prototype.alert = function(){...}
return new obj;
})();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
147 次 |
最近记录: |