![](/img/trans.png)
[英]Is it possible to profile built-in JavaScript functions with Firebug?
[英]Is it possible to detour Built-In JavaScript Function
我正在尝试使用以下代码将参数传递给内置的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");
这段代码以某种方式进行无限递归。
我同意Amin Jafari认为替换内置函数通常不是一个好主意,但可能存在对测试或其他原因有用的情况。
也就是说,您的代码不起作用的原因是您的替换alert()
函数采用以下形式:
function alert( text ) { ... }
在执行相同作用域中的任何其他代码之前处理函数声明。 这有时被称为“功能提升”,尽管这有点用词不当。 (该功能实际上并没有移动 ,术语“吊装”暗示。)
在任何情况下, 在将其保存到built_in_alert
变量之前 ,这将替换内置的alert()
函数。
这样做是这样的:
alert = function( text ) { ... }
因为您现在使用普通的赋值来替换内置的alert()
,所以替换发生在您期望的时间和地点。
试试吧:
built_in_alert = alert; alert = function( text ) { console.log( 'Alert function called with param :'+ text ); built_in_alert( 'Calling with ' + text ); } alert( 'hi' );
如果你不为你的功能使用保留名称,那将是最好的,但如果你真的想这样做(我再说一次是个坏主意)你必须使用window
调用实际的alert()
: DEMO
function alert(text)// Our custom alert function.
{
console.log('Alert function called with param :'+ text);
window.alert("Calling with "+text); // try to call the actual built in alert() function.
return 0;
}
alert("hi");
你可以试试这个:
function custom_alert(text)// Our custom alert function.
{
console.log('Alert function called with param :'+ text);
window.built_in_alert("Calling with "+text);
return 0;
}
if (!window.built_in_alert) {
window.built_in_alert = alert;
window.alert = custom_alert;
}
嗨,你看起来像这样,
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = "hello";
dynamicalert("Custom function "+text )
}
function dynamicalert(_text) {
alert(_text)
}
</script>
</body>
</html>
如果你想使用name属性那么
警报(document.getElementsByName( “用户名”)[0]。价值);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.