javascript给不能修改的函数增加额外处理的方法
不知道是否可行,但姑且google之。 查看到相关的stack overflow(堆栈溢出)帖子:http://stackoverflow.com/questions/1659219/add-to-a-javascript-function 代码拷贝如下:
var originalFn = addToMe;addToMe =function(){ originalFn();// call the original function// other stuff}; addToMe =function(){ originalFn.apply(this, arguments);// preserve the arguments// other stuff}; addToMe =(function(originalFn){returnfunction(){ originalFn.apply(originalFn, arguments);// call the original function// other stuff};})(addToMe);// pass the reference of the original function
时间太晚,只试了一下第一种最简单的无参数的复写:
<html> <head> <title>test</title> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(":input[type='hidden']").bind("propertychange",function(){ alert($(this).val()) }); }); function addRow0(){ alert("simple "); } </script> </head> <body> <form> <input id="hf" type="hidden" value="" /> <input type="button" value="test" onclick="$('#hf').val('fire')" /> <input type="button" value="add hidden field" onclick="" /> <input type="button" value="cache that" onclick="addRow0()" /> </form> </body> <script type="text/javascript"> function addHidden(){ $("body").after("<input type='hidden' id='hf1' />"); } var originalFn = addRow0; addRow0 = function () { originalFn(); alert(" is the best"); } </script> </html>
小伙伴们,有需要可以拿走玩一下。