类与模块

es6 之前,通常使用构造函数来创建对象

// 构造函数 User
function User(username, email) {
this.username = username;
this.email = email;
} // 为了让实例共享方法,将其添加到原型上
User.prototype.changeEmail = function(newEmail) {
this.email = newEmail;
} // 使用
let user = new User("zen", "ihuangmx@qq.com")
user.changeEmail("change@qq.com");
console.log(user.email); //=> "change@qq.com"

而 es6 则可以写成

class User {
// 实例化时,调用 constructor 方法,默认返回 this
constructor(username, email) {
this.username = username;
this.email = email;
} // 类的所有方法会自动绑定到原型对象上,包括 constructor
changeEmail(newEmail) {
this.email = newEmail;
}
} // 使用
let user = new User("zen", "ihuangmx@qq.com")
user.changeEmail("change@qq.com");
console.log(user.email); //=> "change@qq.com"

类中可以定义静态方法,也可以使用 get 与 set 进行访问控制:

class User {
constructor(username, email) {
this.username = username;
this.email = email;
} changeEmail(newEmail) {
this.email = newEmail;
} static register(...args) {
return new User(...args);
} // 等价
// static register(username, email) {
// return new User(username, email);
// } get info() {
return this.username + " " + this.email;
} // 首字符大写
set name(name) {
this.username = name.slice(0,1).toUpperCase().concat(name.slice(1));
} } // 使用
let user = User.register("zen", "ihuangmx@qq.com")
console.log(user.info) // zen ihuangmx@qq.com
user.name = "jack"
console.log(user.info) // Jack ihuangmx@qq.com

类可以作为参数进行传递:

function log(strategy) {
strategy.handle();
} class ConsoleLogger {
handle() {
console.log("log log log");
}
} log(new ConsoleLogger); //=> log log log

模块

在 TaskCollection.js 中定义一个类

class TaskCollection {
constructor(tasks = []) {
this.tasks = tasks;
} dump() {
console.log(this.tasks);
}
}

在 main.js 中使用该类

const tc = new TaskCollection([
'shop',
'eat',
'sleep'
]); tc.dump();

index.html - 显示页面。如果要使其生效的话,在不使用第三方库的情况下,只能将两个文件同时引入

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body> <script src="TaskCollection.js"></script>
<script src="main.js"></script>
</body>
</html>

这样做的话,我们将无法看到彼此间的关联(main.js 加载 TaskCollection.js),因此,es6 提供了解决方案,即模块。通过 export 和 import 来实现

TaskCollection.js - 使用 export 命令显式指定输出的代码

// 输出类
export class TaskCollection {
constructor(tasks = []) {
this.tasks = tasks;
} dump() {
console.log(this.tasks);
}
} // 输出函数
export function foo(){
console.log("foo");
} // 输出变量
export let bar = 123; // 可以统一输出,使其一目了然
// export {TaskCollection, foo, bar};

main.js - 使用 import 加载模块

import { TaskCollection, foo, bar as bar1 } from './TaskCollection';

const tc = new TaskCollection([
'shop',
'eat',
'sleep'
]); tc.dump();
foo();
console.log(bar1);

index.html - 只需要引用 main.js

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body> <script src="main.js"></script>
</body>
</html>

由于当前的浏览器还不支持 es6 语法,我们可以使用打包工具。这里简单的举两个。

rollup.js

全局安装

$ cnpm install --global rollup

使用

$ rollup main.js --format iife --output bundle.js # 针对客户端指定格式为 iife

然后只需要引用生成的 bundle.js

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body> <script src="bundle.js"></script>
</body>
</html>

webpack

安装

$ cnpm install -g webpack

打包

$ webpack main.js bundle.js

或者在当前项目下使用

$ cd webpack-demo-2
$ cnpm install webpack --save-dev

建立配置文件并设置

/webpack-demo-2/webpack.config.js

var webpack = require('webpack');

module.exports = {
entry: './main.js',
output: {
filename: './dist/main.js'
}
}

打包

$ webpack

通常是将其加入到 package.json 中

webpack-demo-2/package.json
{
"devDependencies": {
"webpack": "^2.5.1"
},
"scripts": {
"build": "webpack"
}
}

现在,只需要运行

$ cnpm run build

转换 js

可以注意到,rollup 和 webpack 都仅仅是将其打包,并没有转化为兼容的 js

// 部分打包后的代码
// dist/main.js
"use strict";
/* harmony export (immutable) */ __webpack_exports__["b"] = foo;
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return bar; });
// export 命令显式指定输出的代码
// 输出类
class TaskCollection {
constructor(tasks = []) {
this.tasks = tasks;
} dump() {
console.log(this.tasks);
}
}

这里以 webpack 为例,讲解如何转化为兼容的 js,首先安装相关工具

$ cnpm install --save-dev buble-loader buble

添加

/webpack-demo-2/webpack.config.js

var webpack = require('webpack');

module.exports = {
entry: './main.js',
output: {
filename: './dist/main.js'
},
module: {
loaders: [
{
test: /.js$/,
loaders: 'buble-loader'
}
]
}
}

执行

$ cnpm run build

现在,可以发现已经转化为兼容的 js 了

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return TaskCollection; });
/* harmony export (immutable) */ __webpack_exports__["b"] = foo;
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return bar; });
// export 命令显式指定输出的代码
// 输出类
var TaskCollection = function TaskCollection(tasks) {
if ( tasks === void 0 ) tasks = []; this.tasks = tasks;
}; TaskCollection.prototype.dump = function dump () {
console.log(this.tasks);
};

最新文章

  1. 网络编程4--毕向东java基础教程视频学习笔记
  2. GHOST -ntexact 正常还原
  3. linux安装qwt插件linux
  4. IDEA用maven创建springMVC项目和配置
  5. BZOJ1095(动态点分治+堆)
  6. 如何让多个li居中于ul中间
  7. 搞清Image加载事件(onload)、加载状态(complete)后,实现图片的本地预览,并自适应于父元素内(完成)
  8. 009-Python-面向对象
  9. Linux下apache支持PHP配置
  10. WDA基础十三:常用模板管理
  11. eclipse导出可执行jar包步骤
  12. 2018-2019-20172329 《Java软件结构与数据结构》第五周学习总结
  13. 【Spring Boot&amp;&amp;Spring Cloud系列】Spring Boot配置文件
  14. CentOS 6 - 升级内核
  15. 小tip: base64:URL背景图片与web页面性能优化——张鑫旭
  16. Linux内核的三种调度策略
  17. 搭建psdash 监控系统
  18. 【Linux】Linux各文件夹说明
  19. 【线段树】洛谷 P3372 【模板】线段树 1
  20. TP5 webuploader 单页面多实例上传图片 案例

热门文章

  1. C++ std::vector 总结笔记
  2. netty-socketio(二)整合redis实现发布订阅
  3. 【canvas学习笔记三】样式和颜色
  4. Hbase数据备份&amp;&amp;容灾方案
  5. EventBus-实现java状态机
  6. Spring中基于java的配置
  7. 五、RF中UI自动化操作基础
  8. Putty - 免用户名密码登录
  9. EDM杂谈:第一个屏幕的定义和特点
  10. Stream的并行计算