将数据动态添加到现有函数

问题描述:

我想知道是否可以将数据添加到已在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"); 
    } 

这可能吗?

谢谢。

您可以使用new Function(yourCodeString)创建函数。

但是,这种代码重写是非常混乱的,如果你需要它,你肯定会做错误的!

+0

好的。请参阅我正在编写一个具有onbeforeunload功能的插件。我想确保我的onbeforeunload不会碰撞,如果在我的插件将被集成的页面上有一个。 – Jayesh

+0

至少firefox甚至没有显示onbeforeunload中提供的消息。并且在该函数中使用alert()听起来会非常烦人,因为它将是用户必须单击的两个弹出窗口。 – ThiefMaster

+0

我用警报来测试它是否工作。 – Jayesh