开发环境 babel
- 电脑有node环境,运行
npm init
npm install --save-dev babel-core babel-preset-es2015 babel-preset-latest
- 创建.babelrc文件
{ "presets": ["es2015","latest"], "plugins": [] }
npm install --global babel-cli
babel --version
- 创建./src/index.js
- 内容
[1,2,3].map((item)=>item+1);
- 运行
babel ./src/index.js
开发环境 webpack
npm install webpack babel-loader --save-dev
- 配置webpack.config.js
- 配置package.json 中的scripts
- 运行
npm start
Class和普通构造函数有何区别
Class在语法上更贴合面向对象写法
Class 实现继承更加易读,易理解
本质还是语法糖,使用prototype 实现
- 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,3) 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,3) console.log(m.add())
- 语法糖
typeof MathHandle //function MathHandle === MathHandle.prototype.constructor //true m.__proto__===MathHandle.prototype //true
- 继承
- js继承
function Animal(){ this.eat=function(){console.log('animal eat')} } function Dog(){ this.bark=function(){console.log('Dog bark')} } Dog.prototype=new Animal() var h = new Dog()
- class继承
class Animal { constructor(name) { this.name = name } eat() { console.log(`${this.name} eat`) } } class Dog extends Animal{ constructor(name){ super(name) this.name = name } say(){ console.log(`${this.name} say`) } } const dog = new Dog('哈士奇') dog.say() dog.eat()
- js继承
Promise的基本使用
- Callback Hell
function loadImg(src,callback,fail) { var img = document.createElement('img') img.onload=function () { callback(img) } img.onerror=function () { fail() } img.src =src } var src ="xxxx.jpg" loadImg(src,function (img) { console.log(img.width) },function () { console.log('failed') })
- Promise 语法
function loadImg(src) { const promise = new Promise(function(resolve,reject){ var img = document.createElement('img') img.onload=function () { resolve(img) } img.onerror=function () { reject() } img.src =src }) return promise } var src ="xxx.jpg" var result = loadImg(src) result.then(function(img){ console.log(img.width) },function(){ console.log('failed') }) result.then(function (img) { console.log(img.height) })
其他常用功能总结
- let/const
- 多行字符串/模板变量
- 解构赋值
- 块级作用域
- 函数默认参数
- 箭头函数
function fn() { console.log('real',this)//{a:100} var arr =[1,2,4] //普通js arr.map(function(item){ console.log('js',this) // window return item+1 }) //箭头函数 arr.map(item=>{ console.log('es6',this)// {a:100} return item +1 }) } fn.call({a:100})