gpt4 book ai didi

javascript - 设置 Javascript 函数的范围问题

转载 作者:行者123 更新时间:2023-11-29 10:50:20 25 4
gpt4 key购买 nike

我现在需要“更新”另一个 javascript 文件中存在的函数。该文件如下所示:

function jf(){
alert('1');
}

//call jf periodically
jf();

第二个js文件,加载后是这样的:

console.log(jf);
console.log(window.jf);
var func=function(){
alert('2');
};
jf=func;
window.jf=func;

第一个日志成功返回原来的jf方法,第二个没有。第一组好像设置了局部变量jf,第二组基本什么都不做。有没有办法实现这个功能?

最佳答案

根据 Javascript closures - behavior of overridden functions from the global scope

var done = and function done do basicaly the same thing. They will shadow the outer definition in the inner scope but they will not replace it on the outer scope.

这意味着如果您处于相同的执行上下文中,您只能覆盖 function jf() 的初始定义。否则,将 function jf(){ ... 替换为 window.jf = function(){...

此外,在检查器控制台中运行测试可能会有所帮助。

关于javascript - 设置 Javascript 函数的范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11425355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com