下面,我们直接贴代码,首先,在js文件夹下新建一个first.jsp文件,如下:
const name = "Mike";
function hello() {
console.log("Hello, I'm "+name);
}
然后新建一个second.jsp文件,如下:
const name = "John";
function hello() {
console.log("Hello, I'm "+name);
}
之后我们在JavaScript文件夹下新建一个07_global.html文件,如下:
<!DOCTYPE html>
<html lang="UTF8">
<head>
<meta charset="UTF-8">
<title>全局污染</title>
</head>
<body>
<script type="text/javascript" src="js/first.js"></script>
<script type="text/javascript" src="js/second.js"></script>
<script type="text/javascript">
hello();
</script>
</body>
</html>
此时的运行结果为:
很明显,他只认第一个索引到的hello函数,并且显示name已经被定义了,这就是所谓的全局污染。
那么,我们该怎么解决这个问题呢,很简单,看下边:
修改first.jsp文件如下:
(function () {
const name = "Mike";
function hello() {
console.log("Hello, I'm "+name);
}
window.first = hello();
})();
而second.jsp文件修改如下:
(function () {
const name = "John";
function hello() {
console.log("Hello, I'm "+name);
}
window.second = hello();
})();
window是全局变量,如此设置后,我们就可以顺利调用两个同名的方法,且不让其中的方法和变量因为重名而产生全局污染啦!!!!
这里,我们修改07_global.html文件如下:
<!DOCTYPE html>
<html lang="UTF8">
<head>
<meta charset="UTF-8">
<title>全局污染</title>
</head>
<body>
<script type="text/javascript" src="js/first.js"></script>
<script type="text/javascript" src="js/second.js"></script>
<script type="text/javascript">
first();
second();
</script>
</body>
</html>
此时的运行结果为:
成功啦!!!!惊不惊喜,意不意外!!!