2011-11-25 53 views
0

我想知道是否可以將數據添加到已在Javascript中定義的函數中。將數據動態添加到現有函數

var win; 
    window.onload= function() 
    { 

     win = window.onbeforeunload; 
     win = win.toString(); 

     var firstLetter = win.indexOf('{'); 


     win = win.substring(firstLetter + 1, win.length - 1); 
     //Getting the data of the function [firstLetter = first occurrence of { ] 

     win = win + 'alert("More Unload");'; 

     `/* Here, I want to rebind var win to the window.onbeforeunload event*/` 
    } 

    window.onbeforeunload = function() 
    { 
     alert("Unload function"); 
     alert("More Unload"); 
    } 

這可能嗎?

謝謝。

回答

1

您可以使用new Function(yourCodeString)創建函數。

但是,這種代碼重寫是非常混亂的,如果你需要它,你肯定會做錯誤的!

+0

好的。請參閱我正在編寫一個具有onbeforeunload功能的插件。我想確保我的onbeforeunload不會碰撞,如果在我的插件將被集成的頁面上有一個。 – Jayesh

+0

至少firefox甚至沒有顯示onbeforeunload中提供的消息。並且在該函數中使用alert()聽起來會非常煩人,因爲它將是用戶必須單擊的兩個彈出窗口。 – ThiefMaster

+0

我用警報來測試它是否工作。 – Jayesh