JS-面向对象-封装模块

本文将深入探讨JavaScript中的面向对象编程,重点讲解如何通过封装技术来创建可复用的模块。内容包括类的定义、构造函数、原型链、模块化封装以及实例化过程,帮助开发者提升代码组织和维护效率。
摘要由CSDN通过智能技术生成

<!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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值