ES6语法
问题
ES6模块化如何使用,开发环境如何打包
Class和普通构造函数的区别
Promise的基本使用和原理
总结ES6的常用功能
知识点
模块化与开发环境
模块化的基本语法
export
import
default
开发环境配置
babel配置/babel编译语法
node
npm init
npm install --save-dev babel-core babel-preset-es2015 babel-preset-latest //安装babel相关依赖
.babelrc //创建.babelrc文件
{
"presets": ["es2015", "latest"],
"plugins": []
}
npm install -g babel-cli //win管理员模式
babel --version //查看babel版本
./src/index.js //创建文件
babel ./src/index.js //编译
Webpack配置/模块化工具
npm install webpack babel-loader --save-d
webpack.config.js //新建,配置
package.json中scripts //配置
npm start
*rollup
JS众多模块化的标准
没有模块化
AMD成为标准 require.js /(CMD)
前端打包工具,使node.js模块化也可以被使用
ES6想统一现所有模块化标准
node.js积极支持,浏览器端尚未统一
可以自建lib,不要自建标准
Class与JS普通构造函数
JS构造函数
function MathHandle(x, y) {
this.x = x
this.y = y
} //构造函数
MathHandle.prototype.add = function () {
return this.x + this.y
}//原型中定义了方法
var m = new MathHandle(1, 2)//实例化了一个m
console.log(m.add())
Class基本语法
例子:
class MathHandle {
constructor(x, y) {
this.x = x;
this.y = y;
}
add() {
return this.x + this.y;
}
}
const m = new MathHandle(1, 2);
console.log(m.add());
重点
typeof MathHandle //'function'
MathHandle.prototype.constructor === MathHandle //true 构造函数有显式原型 显式原型的constructor属性等于构造函数本身
m.__proto__ === MathHandle.prototype //true new出来的实例有隐式原型,等于构造函数的显式原型
语法糖
class MathHandle {
//……
}
重点
typeof MathHandle // 'function' class本身就是function
MathHandle.prototype.constructor === MathHandle // true
m.__proto__ === MathHandle.prototype // true
继承
低级函数的原型赋值给高级构造函数的实例
// 动物
function Animal() {
this.eat = function () {
alert('Animal eat')
}
}
// 狗
function Dog() {
this.bark = function () {
alert('Dog bark')
}
}
// 绑定原型,实现继承
Dog.prototype = new Animal() //初始化一个Animal实例赋值给Dog的显式原型中
var hashiqi = new Dog()
hashiqi.bark()
hashiqi.eat()
Class
class Animal {
constructor(name) {
this.name = name
}
eat() {
alert(this.name + ' eat')
}
}
class Dog extends Animal {
constructor(name) {
super(name) // 注意 !!!extends super
this.name = name
}
say() {
alert(this.name + ' say')
}
}
const dog = new Dog('哈士奇')
dog.say()
dog.eat()
总结
class语法上贴合面向对象的写法
class实现继承上更加简单 易理解
易于写java等后端语言的使用
本质语法糖,使用prototype
Promise原理与使用
适用于异步编程
Callback Hell
Promise语法
ES6的一些常用功能
let/const
多行字符串/模板变量
解构赋值
块级作用域
函数默认参数
箭头函数
箭头函数“绑定”this