覆盖现有的 JavaScript 函数
Overwrite an existing JavaScript function
我有一个名为 GlobalAll() 的现有全局 JavaScript 函数。默认情况下,该功能在每个页面上加载。
function GlobalAll(){alert("I am Global!");}
这个函数没有 return 任何东西。在某些页面上,我想重新定义此函数,以便它改为提醒 "I am Local!" 或根本不提醒。函数名称需要保持不变,因为它比仅仅提醒某些东西更复杂。
所以,从技术上讲,我们需要的是 rewrite/overwrite 这个全局函数,并在特定页面中以相同的名称调用它。
有什么解决办法吗?
由于 DOM 按顺序从上到下加载,只需在您最初定义它的下方的某个位置重新定义它即可。
所以:
<body>
<script src="something.js"></script> <!-- defines GlobalAll() -->
<script>
function GlobalAll() {
alert('I am local');
}
</script>
</body>
您可以在每个单独的页面上为 GlobalAll 定义专门的行为。只需确保新定义在旧定义之后,javascript 应该使用较新的定义。
让我们支持你有一个名为 global.js 的 javascript 文件。在里面,你有一个 GlobalAll
函数:
function GlobalAll() {
alert("I am Global");
}
假设你有这个 html:
<html>
<head>
<script type="text/javascript" src="/js/global.js"></script>
</head>
<body>
</body>
</html>
你正在某处调用 GlobalAll
,所以你必须有类似的东西:
<html>
<head>
<script type="text/javascript" src="/js/global.js"></script>
<script type="text/javascript">
GlobalAll();
</script>
</head>
<body>
</body>
</html>
这提醒 I am Global
。您需要在最初定义函数后覆盖该函数,以确保您的本地函数覆盖全局函数,并且您需要在调用它之前覆盖该函数,以确保在调用它时使用正确的实例:
<html>
<head>
<script type="text/javascript" src="/js/global.js"></script>
<script type="text/javascript">
function GlobalAll() {
alert("I am Local");
}
GlobalAll();
</script>
</head>
<body>
</body>
</html>
我有一个名为 GlobalAll() 的现有全局 JavaScript 函数。默认情况下,该功能在每个页面上加载。
function GlobalAll(){alert("I am Global!");}
这个函数没有 return 任何东西。在某些页面上,我想重新定义此函数,以便它改为提醒 "I am Local!" 或根本不提醒。函数名称需要保持不变,因为它比仅仅提醒某些东西更复杂。
所以,从技术上讲,我们需要的是 rewrite/overwrite 这个全局函数,并在特定页面中以相同的名称调用它。
有什么解决办法吗?
由于 DOM 按顺序从上到下加载,只需在您最初定义它的下方的某个位置重新定义它即可。
所以:
<body>
<script src="something.js"></script> <!-- defines GlobalAll() -->
<script>
function GlobalAll() {
alert('I am local');
}
</script>
</body>
您可以在每个单独的页面上为 GlobalAll 定义专门的行为。只需确保新定义在旧定义之后,javascript 应该使用较新的定义。
让我们支持你有一个名为 global.js 的 javascript 文件。在里面,你有一个 GlobalAll
函数:
function GlobalAll() {
alert("I am Global");
}
假设你有这个 html:
<html>
<head>
<script type="text/javascript" src="/js/global.js"></script>
</head>
<body>
</body>
</html>
你正在某处调用 GlobalAll
,所以你必须有类似的东西:
<html>
<head>
<script type="text/javascript" src="/js/global.js"></script>
<script type="text/javascript">
GlobalAll();
</script>
</head>
<body>
</body>
</html>
这提醒 I am Global
。您需要在最初定义函数后覆盖该函数,以确保您的本地函数覆盖全局函数,并且您需要在调用它之前覆盖该函数,以确保在调用它时使用正确的实例:
<html>
<head>
<script type="text/javascript" src="/js/global.js"></script>
<script type="text/javascript">
function GlobalAll() {
alert("I am Local");
}
GlobalAll();
</script>
</head>
<body>
</body>
</html>