前端(四)ES6篇

es6篇


推薦 CrazyCodeBoy的文章 ES六、ES七、ES8特性一鍋燉(ES六、ES七、ES8學習指南)前端

一、ES6+你熟悉麼,用過哪些特性?

  • 箭頭函數
  • 類及引入導出和繼承( class/import/export/extends)
  • 字符串模板
  • Promise
  • let,const
  • async/await
  • 模塊化
  • 解構賦值
  • 延展操做符
  • 對象屬性簡寫

二、let 和 const 有啥差別?

  • let 會產生塊級做用域,不會形成變量提高,沒法從新聲明(但能夠從新賦值);
  • const是常量,如果基本數據類型,具備不變性(沒法從新賦值改動) 引用值能夠調整內部值(可能設計的時候沒有考慮周全!

三、async和await的用途?

promise 的異步變成同步運行成了可能,await 能夠等到 promise 執行完畢es6

四、類、繼承

class Animal {
    // 構造函數,實例化的時候將會被調用,若是不指定,那麼會有一個不帶參數的默認構造函數.
    constructor(name,color) {
      this.name = name;
      this.color = color;
    }
    // toString 是原型對象上的屬性
    toString() {
      console.log('name:' + this.name + ',color:' + this.color);

    }
  }

 var animal = new Animal('dog','white');//實例化Animal
 animal.toString();

 console.log(animal.hasOwnProperty('name')); //true
 console.log(animal.hasOwnProperty('toString')); // false
 console.log(animal.__proto__.hasOwnProperty('toString')); // true

 class Cat extends Animal {
  constructor(action) {
    // 子類必需要在constructor中指定super 函數,不然在新建實例的時候會報錯.
    // 若是沒有置頂consructor,默認帶super函數的constructor將會被添加、
    super('cat','white');
    this.action = action;
  }
  toString() {
    console.log(super.toString());
  }
 }

 var cat = new Cat('catch')
 cat.toString();

 // 實例cat 是 Cat 和 Animal 的實例,和Es5徹底一致。
 console.log(cat instanceof Cat); // true
 console.log(cat instanceof Animal); // true

複製代碼

五、模塊化(Module)

模塊的功能主要由 export 和 import 組成。

每個模塊都有本身單獨的做用域,模塊之間的相互調用關係是經過 export 來規定模塊對外暴露的接口,經過import來引用其它模塊提供的接口。同時還爲模塊創造了命名空間,防止函數的命名衝突。面試

  • 導出(export)

ES6容許在一個模塊中使用export來導出多個變量或函數。ajax

1)導出變量json

//test.js
export var name = 'Rainbow'

複製代碼

2)導出函數api

// myModule.js
export function myModule(someArg) {
  return someArg;
}  

複製代碼
  • 導入(import)
import {myModule} from 'myModule';// main.js
import {name,age} from 'test';// test.js

複製代碼

六、箭頭函數this指向誰

箭頭函數所改變的並不是把 this 局部化,而是徹底不把 this 綁定到裏面去;promise

就是 this 是取自外部的上下級做用域(可是又不是常規 function的語法糖)..bash

由於箭頭函數裏並不支持var self = this 或者 .bind(this)這樣的寫法。app

七、普通函數和箭頭函數的區別

  • this指向的問題,會捕獲其所在上下文的 this 值,做爲本身的 this 值。
  • 箭頭函數不綁定 arguments,取而代之用rest參數解決。
var foo = (...args) => {
  return args[0]
}
console.log(foo(1)) 
複製代碼
  • 箭頭函數不能用做構造器,和 new一塊兒用就會拋出錯誤。
  • 箭頭函數沒有原型屬性。
var foo = () => {};
console.log(foo.prototype) //undefined
複製代碼

八、靜態方法,靜態屬性,私有變量麼?

靜態方法是ES6以後纔有這麼個玩意,有這麼些特色異步

  • 方法不能給 this引用,能夠給類直接引用
  • 靜態不能夠給實例調用,好比 let a = new ParentClass => a.sayHello() 會拋出異常
  • 父類靜態方法,子類非static方法無法覆蓋父類
  • 靜態方法能夠給子類繼承
  • 靜態屬性能夠繼承也能夠被修改
class ParentClass {
      constructor(name) {
        this.name = name;
      }
      static sayHello() {
        console.log("I'm parent!" + this.name);
      }

      static testFunc(){
        console.log('emm...Parent test static Func')
      }
    }

    class SubClass extends ParentClass {
      constructor(name) {
        super(name);
      }
      sayChildHello() {
        console.log("I'm child " + this.name)
      }
      static sayHello() {
        console.log("override parent method !,I'm sayHello Method")
      }

      static testFunc2() {
        console.log(super.testFunc() + 'fsdafasdf');
      }
    }
    ParentClass.sayHello(); // success print

    let a = new ParentClass('test');
    a.sayHello() // throw error

    SubClass.sayHello(); // 同名 static 能夠繼承且覆蓋
    
    SubClass.testFunc2(); // 能夠繼承

    let testA = new SubClass('CRPER');


複製代碼

私有變量

WeakMap能夠避免內存泄露,當沒有被值引用的時候會自動給內存寄存器回收了.

const _ = new WeakMap(); // 實例化,value 必須爲對象,有 delete,get,has,set四個方法,看名字都知道了

class TestWeakMap {
  constructor(id, barcode) {
    _.set(this, { id,barcode });
  }
  testFunc() {
    let { id,barcode } = _.get(this); // 獲取對應的值
    return { id,barcode };
  }
}


複製代碼

用Symbol來實現一個私有變量

九、談談你對 Promise 的理解? 和 ajax 有關係麼?

Promiseajax沒有半毛錢直接關係.promise只是爲了解決"回調地獄"而誕生的; 平時結合 ajax是爲了更好的梳理和控制流程...這裏咱們簡單梳理下..

es6 promise ajax

定義
const myHttpClient = url => {
  return new Promise((resolve, reject) => {
    let client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");
    client.send();
    function handler() {
      if (this.readyState !== 4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    }
  });
};
使用
myHttpClient('https://www.baidu.com').then(res => {
  console.log(res);
}).catch(error => {
  console.log(error);
});

複製代碼

Promise有三種狀態,Pending/resolve()/reject();

一些須要注意的小點,以下

  • Pending轉爲另外兩種之一的狀態時候,狀態不可在改變..
  • Promisethen爲異步.而(new Promise())構造函數內爲同步
  • Promisecatch不能捕獲任意狀況的錯誤(好比 then 裏面的setTimout內手動拋出一個Error)
  • Promisethen返回Promise.reject()會中斷鏈式調用 -Promiseresolve如果傳入值而非函數,會發生值穿透的現象
  • Promisecatch仍是then,return的都是一個新的 Promise(在 Promise 沒有被中斷的狀況下)

Promise 還有一些自帶的方法,好比race,all,前者有任一一個解析完畢就返回,後者全部解析完畢返回...

十、實現一個 promise

首先你須要對 promise 有一個清晰的認識,封裝過請求,使用過它的 api 等。

請參考 前端勸退師 的文章 「中高級前端面試」JavaScript手寫代碼無敵祕籍

25行代碼實現Promise函數

十一、實現一個按順序加載的 promise

當你說出 promise.allpromise.race的區別後,面試官可能就會接着考察此題。

/* 使用 async await */
async function queue(tasks) {
  const res = []
  for (let promise of tasks) {
    res.push(await promise(res));
  }
  return await res
}
queue([a, b, c])
  .then(data => {
    console.log(data)
  })

複製代碼

十二、實現一個 sleep 函數

//Promise
const sleep = time => {
  return new Promise(resolve => setTimeout(resolve,time))
}
sleep(1000).then(()=>{
  console.log(1)
})
複製代碼
//Generator
function* sleepGenerator(time) {
  yield new Promise(function(resolve,reject){
    setTimeout(resolve,time);
  })
}
sleepGenerator(1000).next().value.then(()=>{console.log(1)})
複製代碼
//async
function sleep(time) {
  return new Promise(resolve => setTimeout(resolve,time))
}
async function output() {
  let out = await sleep(1000);
  console.log(1);
  return out;
}
output();

複製代碼
//ES5
function sleep(callback,time) {
  if(typeof callback === 'function')
    setTimeout(callback,time)
}

function output(){
  console.log(1);
}
sleep(output,1000);

複製代碼

1三、題目

Promise 必知必會(十道題): 有助於你更加深入的瞭解 promise 的運行狀況

關於 Promise 的 9 個提示

更多的Promise 詳情能夠參考JavaScript Promise迷你書(中文版);

相關文章
相關標籤/搜索