我正在尝试使用以下代码将参数传递给内置的JavaScript函数alert().一旦我将参数传递给它,现在我想调用真正的(内置)函数,这样代码就不会中断.
built_in_alert = alert;
function alert(text)// Our custom alert function.
{
console.log('Alert function called with param :'+ text);
built_in_alert("Calling with "+text) // try to call the actual built in alert() function.
return 0;
}
alert("hi");
Run Code Online (Sandbox Code Playgroud)
这段代码以某种方式进行无限递归.
我同意Amin Jafari认为替换内置函数通常不是一个好主意,但可能存在对测试或其他原因有用的情况.
也就是说,您的代码不起作用的原因是您的替换alert()函数采用以下形式:
function alert( text ) { ... }
Run Code Online (Sandbox Code Playgroud)
在执行相同作用域中的任何其他代码之前处理函数声明.这有时被称为"功能提升",尽管这有点用词不当.(该功能实际上没有移动的术语"吊装"暗示.)
在任何情况下,这都会在将内置alert()函数保存到变量中之前替换它built_in_alert.
这样做是这样的:
alert = function( text ) { ... }
Run Code Online (Sandbox Code Playgroud)
因为您现在使用普通任务来替换内置命令alert(),所以替换发生在您期望的时间和地点.
试试吧:
built_in_alert = alert;
alert = function( text ) {
console.log( 'Alert function called with param :'+ text );
built_in_alert( 'Calling with ' + text );
}
alert( 'hi' );Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
167 次 |
| 最近记录: |