设计模式:模块模式

摸块化模式最初被定义为在传统软件工程中为类提供私有和公共封装的一种方法。
能够使一个单独的对象拥有公共/私有的方法和变量,从而屏蔽来自全局作用域的特殊部分。这可以减少我们的函数名与在页面中其他脚本区域内定义的函数名冲突的可能性。

模块化的两种实现方式

闭包

在这里插入图片描述

    let module = (function () {
      let count = 0
      let increment = function () {
        return ++count
      }
      let decrement = function () {
        return --count
      }

      return {
        increment,
        decrement
      }
    })()


    console.log(module.decrement())
    console.log(module.increment())
    console.log(module.increment());

模块化

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script type="module">
    import counter from './2.js'
    console.log(counter.increment())
    console.log(counter.increment())
    console.log(counter.decrement());
  </script>
</body>

</html>

2.js

let count = 0
let increment = function () {
  return ++count
}
let decrement = function () {
  return --count
}


export default {
  increment,
  decrement
}

在这里插入图片描述

注意:如果本地跑上面实例代码报下面的错

Access to script at ‘file:///C:/xampp/htdocs/myblog/web/%E5%AD%A6%E4%B9%A0/2019-11-20nodejs01/ code /%E4%B8%8A%E6%AC%A1%E5%86%85%E5%AE%B9/es6%E6%A8%A1%E5%9D%97%E5%8C%96/a.js’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

解决方法:
vscode安装Live Server
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值