ES6常用知识点积累

概述

ECMAScript 6(以下简称ES6)是JavaScript语言的下一代标准。因为当前版本的ES6是在2015年发布的,所以又称ECMAScript 2015。

let,const

都是用来声明变量的,对应ES5的var,但是特性更好:

let

var name = 'zach'
while (true) {
   var name = 'obama'
   console.log(name)  //obama
   break
}
console.log(name)  //obama

ES5的var只有全局作用域和函数作用域,这样容易导致某些情况下全局变量被方法更改的问题。而let则是块级作用域,不影响全局变量。如:

let name = 'zach'
while (true) {
   let name = 'obama'
   console.log(name)  //obama
   break
}
console.log(name)  //zach

另外一个var带来的不合理场景就是用来计数的循环变量泄露为全局变量,看下面的例子:

var a = [];
for (var i = 0; i < 10; i++) {
 a[i] = function () {
   console.log(i);
 };
}
a[6](); // 10

上面的代码中 变量i是var声明的,在全局范围内都有效。所以每次循环,需要输出的i都会累加。到最后所有的方法指向的都是最后的i=10。而如果使用let则不会出现这个问题

var a = [];
for (let i = 0; i < 10; i++) {
 a[i] = function () {
   console.log(i);
 };
}
a[6](); // 6

再来看一个例子:不用ES6

let clickBoxs = document.querySelectorAll('.btn')
for (var i = 0; i < clickBoxs.length; i++) {
    clickBoxs[i].onclick = function () {
        console.log(i)
    }
}

点击不同的clickBox显示不同的i,上面的例子,点击任何一个按钮都是等于clickBoxs.length
下面来解决它:

function iteratorFactory(i) {
    var onclick = function (e) {
        console.log(i)
    }
    return onclick;
}
var clickBoxs = document.querySelectorAll('.btn2')
for (var i = 0; i < clickBoxs.length; i++) {
    clickBoxs[i].onclick = iteratorFactory(i)
}

而如果使用ES6则只要将对应的var改为let即可。不用这么麻烦。

const

const使用时必须在声明处赋值,并且之后不能做更改。比较常用的用法是用来声明工具对象。如const util=require(‘moment’)
防止该对象被更改避免错误。

class,extends,super

类似于java中的用法:

class Animal {
    constructor() {
        this.type = 'animal'
    }
    says(say) {
        console.log(this.type + ' says ' + say)
    }
}
let animal = new Animal()
animal.says("miao~")//animal says miao~
class People extends Animal {
    constructor() {
        super()
        this.type = "people"
    }
}
let people = new People()
people.says("hello")//people says hello

super关键字,大知道父类的实例(即父类的this对象)。自雷必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为自雷没有自己的this对象。而是继承父类的this对象然后再加工。

ES6的继承机制,实质是先创造父类的实例对象this(所以必须先调用super方法),然后再用子类的构造函数修改this。

箭头函数

优点:

  1. 简洁(如果没有{}符号,则表达式的结果为方法返回值return)
  2. 创建时this对象使用当时定义时所在的对象。(普通方法是调用时的对象)
function(i){ return i + 1; } //ES5
(i) => i + 1 //ES6 

如果方法比较复杂,则需要在箭头后面加上{}如:

function(x, y) {
   x++;
   y--;
   return x + y;
}
(x, y) => {x++; y--; return x+y}

this对象问题:

class Animal {
    constructor() {
        this.type = 'animal'
    }
    says(say) {
        setTimeout(function () {
            console.log(this.type + ' says ' + say)
        }.bind(this), 1000)
    }
}
var animal = new Animal()
animal.says('hi')  //undefined says hi

在ES5中该方法执行会报错,因为执行延迟后方法中的this指向全局对象。
解决方法有两种:

  1. 将this对象传给变量,再在延迟过后使用该对象
says(say){
  var self = this;
  setTimeout(function(){
      console.log(self.type + ' says ' + say)
  }, 1000)

2.使用bind(this)

 says(say){
  setTimeout(function(){
      console.log(this.type + ' says ' + say)
  }.bind(this), 1000)

3.使用箭头函数:

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

模版字符串

··符号,ES5中的写法是字符串需要+=或者合成一个长串,不便于阅读又十分麻烦。而使用模版字符串,则大大简化。

$("#result").append(
 "There are <b>" + basket.count + "</b> " +
 "items in your basket, " +
 "<em>" + basket.onSale +
 "</em> are on sale!"
);

模板字符串:(变量使用${})

$("#result").append(`
 There are <b>${basket.count}</b> items
  in your basket, <em>${basket.onSale}</em>
 are on sale!
`);

解构

ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。

let student = "stu"
let teacher = "tea"

let classRoom = {student: student, teacher: teacher}//es5
console.log(classRoom)//{student: "stu", teacher: "tea"}

let classRoom1 = {student, teacher}//es6
console.log(classRoom1)//{student: "stu", teacher: "tea"}

使用ES6,如果key等于对象名,则可以这样

let cat = 'ken'
let dog = 'lili'
let zoo = {cat, dog}
console.log(zoo)  //Object {cat: "ken", dog: "lili"}

相反,可以这样写:相当于从对象中取出该对象key并赋值

let dog = {type: 'animal', many: 2}
let { type, many} = dog
console.log(type, many)   //animal 2

default,rest

default默认值,即在方法传入时,如果入参为空,可以指定一个默认值

//传统写法
function animal(type){
   type = type || 'cat'  
   console.log(type)
}
animal() //cat
//ES6写法
function animal(type='cat'){
    console.log(type)
}

rest语法:将传入的对象都放入数组中,如果入参为空,则types是一个空数组

function animals(...types){
   console.log(types)
}
animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]

import,export

导入、导出。ES6模块的设计思想,是尽量的静态化,使得编译时就能确定模块的依赖关系,以及输入和输出的变量。
用法:

//index.js
import animal from './content'

//content.js
export default 'A cat'

其他高级用法:

//content.js
export default 'A cat'    
export function say(){
   return 'Hello!'
}    
export const type = 'dog'

exprot除了可以输出变量,输出函数,还能输出类(react中基本都是输出类)

//index.js

import { say, type } from './content'  
let says = say()
console.log(`The ${type} says ${says}`)  //The dog says Hello

如果还希望输入content.js中输出的默认值(default), 可以写在大括号外面。

//index.js

import animal, { say, type } from './content'  
let says = say()
console.log(`The ${type} says ${says} to ${animal}`)  
//The dog says Hello to A cat
  • 修改improt的变量名(当有重名的变量时可用,as)
//index.js

import animal, { say, type as animalType } from './content'  
let says = say()
console.log(`The ${animalType} says ${says} to ${animal}`)  
//The dog says Hello to A cat
  • 使用号整体加载,通常星号结合as一起使用比较合适。
//index.js

import animal, * as content from './content'  
let says = content.say()
console.log(`The ${content.type} says ${says} to ${animal}`)  
//The dog says Hello to A cat

计算属性名称语法:

对象的属性名,可以像数组下标一样使用[]符号获取对应的属性值。并且[]符号内容可以是变量
也可以进行计算,取计算的结果作为取值key

var i = 0;
var a = {
  ['foo' + ++i]: i,
  ['foo' + ++i]: i,
  ['foo' + ++i]: i
};

console.log(a.foo1); // 1
console.log(a.foo2); // 2
console.log(a.foo3); // 3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值