2013-02-21 81 views
1

我正在閱讀關於JavaScript刪除操作符和試驗。一切似乎都很好,直到我試圖從窗口對象中刪除一個方法。代碼看起來像下面window.alert無法刪除

var log = function(str){ 
    if(str !== undefined) 
    { 
    document.write(str); 
    } 
    document.write("</br>"); 
}; 


window.myVar = function(){ 
    // do something 
}; 

// this deletes custom method 
log(delete window.myVar); // true (expected) 
log(typeof window.myVar); // undefined (expected) 

log(delete window.alert); // true (OK) 
log(typeof window.alert); // function (Unexpected) 

window.alert = 10; 
log(typeof window.alert); // number (Successfully overwritten) 
log(delete window.alert); // true 
log(typeof window.alert); // function (Returns back to original object) 

看來,它讓我刪除我創建的對象,但尚未定義的對象,但它讓我重寫它。有人可以解釋我背後的原因是什麼?如果刪除的對象在這裏也沒有發生,也應該返回'false'。

[更新]我用的FF 19和運行它http://jsbin.com

[更新]請注意,我知道如何重寫window.alert和運行我的自定義代碼。我的問題是關於window.alert是如此特別,以至於它不能被刪除,但刪除返回true?我知道這是一個本地對象,但這並不能解釋爲什麼這是不可能的。瀏覽器JavaScript引擎在被我的代碼刪除後是否重新添加了警報方法?也有可能我寫類似的功能,使其他用戶使用我的圖書館不能刪除,但只能覆蓋?怎麼樣?

+1

原生功能不能被刪除。你想做什麼? – sdespont 2013-02-21 08:51:22

+0

我明白這不應該在實際的代碼中完成,但我在這裏試圖從技術上確切地知道發生了什麼,以及它是否使用了一些JavaScript功能,那些功能是什麼,以及如果可以在自定義代碼/庫中使用這些功能 – Tanmoy 2013-02-21 09:19:10

回答

1

很簡單,我們可以覆蓋現有的功能但不能刪除它們。現有的/標準功能被重置爲標準原型,而不是在對其調用時刪除。但是,如果你想以中和功能說windows.alert然後分配一個空白的功能象下面這樣:

window.alert = function(){}; //blank function makes window.alert now useless 

嘗試控制檯(瀏覽器)基於腳本:

window.alert = function(data){ 
    console.log('alerting:'+data) 
}; 
window.alert('hi'); // this will print "alerting:hi" in console 
delete window.alert 
window.alert('hi'); // now this will show regular alert message box with "hi" in it 

我希望這可以解釋它。

UPDATE:

比方說,你要覆蓋一個標準功能 「警報」,則:

//this function will append the data recieved to a HTML element with 
// ID message-div instead of showing browser alert popup 
window.alert = function(data){ 
    document.getElementById('message-div').innerHTML = data; 
} 
alert('Saved Successfully'); //usage as usual 
... 
//when you no longer need custom alert then you revert to standard with statement below 
delete window.alert; 
+0

爲什麼'log(delete window.alert); //返回true'? – SparKot 2013-02-21 08:52:40

+0

它會返回true,因爲像alert這樣的函數會將其恢復爲默認狀態。 – 2013-02-21 09:03:19

+0

「我們可以覆蓋現有的功能,但不能抹去它們」 - 從技術上來說,這是如何完成的?它是否使用一些公開的JavaScript方式來做到這一點?在這種情況下,我可以在我的自定義代碼中使用它嗎? – Tanmoy 2013-02-21 09:21:58