<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
// 你写的代码为位于 index1.js 文件中
// var foo = 'Hello World!'
// 我写的代码为位于 index2.js 文件中
// var foo = '你好,世界!'
// 你和我的 index 文件同时被引入到了同一个 index.html 文件中,会发生什么情况?
// 最后引入的那个文件中 foo 变量会被之前文件中 foo 变量覆盖掉。
// window.foo = 'Hello World!'; // 前脚刚给 window 对象添加了一个新属性 foo,并赋值为 'Hello World!'
// window.foo = '你好,世界!'; // 后脚就立马将 foo 属性的值修改成了 '你好,世界!'
// 为了解决这个问题,我们可以将这两个 foo 分别放到两个不同的模块(函数作用域)中,如以下代码所示:
// index1.js
var module1 = (function () {
var foo = 'Hello World!';
function max (x, y) {
return x > y ? x : y;
}
return {
foo,
max
};
}())
// index1.js
var module2 = (function () {
var foo = '你好,世界!';
function min (a, b) {
return a < b ? a : b;
}
return {
foo,
min
};
}())
// 分别使用不同模块下的 foo 变量
console.log(module1.foo)
console.log(module2.foo)
</script>
</body>
</html>
JS-面向对象-封装模块
最新推荐文章于 2023-07-25 09:02:13 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)