首页 > 代码库 > ES6阅读笔记
ES6阅读笔记
一.babel转换器:babel.js.io;
二.变量声明.
1.块级作用域let:
传统var声明:
var a = []; for (var i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 10
变量let声明:
var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 6
2.常量const:一旦声明不可改变,一般用来引入模块,例如:const moment=require("moment");
三.类Class
class Animal { constructor(){ this.type = ‘animal‘ } says(say){ console.log(this.type + ‘ says ‘ + say) } } let animal = new Animal() animal.says(‘hello‘) //animal says hello class Cat extends Animal { constructor(){ super()//指代父类的实例,必须要有。 this.type = ‘cat‘ } } let cat = new Cat() cat.says(‘hello‘) //cat says hello
四.箭头函数arrow function
1.简化写法
function(x, y) { x++; y--; return x + y; }//es5 (x, y) => {x++; y--; return x+y}//es6
2.使用箭头函数时,函数体内的this对象,就是定义时所在的对象,看例题:
class Animal { constructor(){ this.type = ‘animal‘ } says(say){ setTimeout(function(){ console.log(this.type + ‘ says ‘ + say) }, 1000) } } var animal = new Animal() animal.says(‘hi‘) //undefined says hi,因为setTimeout中的this对象指向全局对象,在ES5中一般是把this赋值给常量然后代入,或者使用.bind(this) class Animal { constructor(){ this.type = ‘animal‘ } says(say){ setTimeout( () => { console.log(this.type + ‘ says ‘ + say) }, 1000) } } var animal = new Animal() animal.says(‘hi‘) //animal says hi
五.template string:简化拼接字符串写法
$("#result").append( "There are <b>" + basket.count + "</b> " + "items in your basket, " + "<em>" + basket.onSale + "</em> are on sale!" );//es5中,使用拼接字符串形式 $("#result").append(` There are <b>${basket.count}</b> items in your basket, <em>${basket.onSale}</em> are on sale! `);//es6中,将字符串放在单引号内,变量则放在${}中
六.解构:destructuring:允许按照一定模式,从数组和变量中取得值,对变量进行赋值.
let cat = ‘ken‘ let dog = ‘lili‘ let zoo = {cat: cat, dog: dog} console.log(zoo) //Object {cat: "ken", dog: "lili"},es5 let cat = ‘ken‘ let dog = ‘lili‘ let zoo = {cat, dog} console.log(zoo) //Object {cat: "ken", dog: "lili"},es6
反过来:
let dog = {type: ‘animal‘, many: 2}
let { type, many} = dog
console.log(type, many) //animal 2
七.default默认值
function animal(type){ type = type || ‘cat‘ console.log(type) } animal()//es5 function animal(type = ‘cat‘){ console.log(type) } animal()//es6
rest
function animals(...types){ console.log(types) } animals(‘cat‘, ‘dog‘, ‘fish‘) //["cat", "dog", "fish"]
ES6阅读笔记
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。