面试总结(1):es6相关

本文详细介绍了ES6的新特性,包括let和const声明变量、class类的使用、继承机制、箭头函数、解构赋值及Promise等。通过具体示例展示了如何利用这些新特性来简化JavaScript编程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

es6 新特性

  • let const

  • class, extends, super

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

    constructor内定义的方法和属性是实例对象自己的,而constructor外定义的方法和属性则是所有实力对象可以共享的。

    下面定义了一个Cat类,该类通过extends关键字,继承了Animal类的所有属性和方法。

    super关键字,它指代父类的实例(即父类的this对象)。子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。

    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 箭头函数

    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

    箭头函数没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。

  • destructuring 解构

    从数组和对象中提取值,对变量进行赋值

    let cat = 'ken'
    let dog = 'lili'
    let zoo = {cat, dog}
    console.log(zoo)  //Object {cat: "ken", dog: "lili"}
    
    let dog = {type: 'animal', many: 2}
    let { type, many} = dog
    console.log(type, many)   //animal 2
  • default, rest

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

Promise

ES6 规定,Promise对象是一个构造函数,用来生成Promise实例。

let promise = new Promise(function(resolve, reject) {
  console.log('Promise');
  resolve();
});

promise.then(function() {
  console.log('Resolved.');
});

console.log('Hi!');

// Promise
// Hi!
// Resolved

Promise 新建后立即执行,所以首先输出的是Promise。然后,then方法指定的回调函数,将在当前脚本所有同步任务执行完才会执行,所以Resolved最后输出。

promise 好复杂。。。。未完待续。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值