es6篇
推荐 CrazyCodeBoy的文章 ES六、ES七、ES8特性一锅炖(ES六、ES七、ES8学习指南)前端
Promise
let
,const
async/await
let
会产生块级做用域,不会形成变量提高,没法从新声明(但能够从新赋值);const
是常量,如果基本数据类型,具备不变性(没法从新赋值改动) 引用值能够调整内部值(可能设计的时候没有考虑周全!让 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
复制代码
模块的功能主要由 export 和 import 组成。
每个模块都有本身单独的做用域,模块之间的相互调用关系是经过 export
来规定模块对外暴露的接口,经过import
来引用其它模块提供的接口。同时还为模块创造了命名空间,防止函数的命名冲突。面试
ES6容许在一个模块中使用export来导出多个变量或函数。ajax
1)导出变量json
//test.js
export var name = 'Rainbow'
复制代码
2)导出函数api
// myModule.js
export function myModule(someArg) {
return someArg;
}
复制代码
import {myModule} from 'myModule';// main.js
import {name,age} from 'test';// test.js
复制代码
箭头函数所改变的并不是把 this 局部化,而是彻底不把 this 绑定到里面去;promise
就是 this 是取自外部的上下级做用域(可是又不是常规 function的语法糖)..bash
由于箭头函数里并不支持var self = this
或者 .bind(this)
这样的写法。app
arguments
,取而代之用rest参数
解决。var foo = (...args) => {
return args[0]
}
console.log(foo(1))
复制代码
new
一块儿用就会抛出错误。var foo = () => {};
console.log(foo.prototype) //undefined
复制代码
静态方法是ES6以后才有这么个玩意,有这么些特色异步
非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
没有半毛钱直接关系.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
转为另外两种之一的状态时候,状态不可在改变..Promise
的 then
为异步.而(new Promise())构造函数内为同步Promise
的catch
不能捕获任意状况的错误(好比 then 里面的setTimout内手动抛出一个Error)Promise
的then
返回Promise.reject()
会中断链式调用 -Promise
的 resolve
如果传入值而非函数,会发生值穿透的现象Promise
的catch
仍是then
,return
的都是一个新的 Promise
(在 Promise 没有被中断的状况下)Promise 还有一些自带的方法,好比race,all,前者有任一一个解析完毕就返回,后者全部解析完毕返回...
首先你须要对 promise 有一个清晰的认识,封装过请求,使用过它的 api 等。
请参考 前端劝退师
的文章 「中高级前端面试」JavaScript手写代码无敌秘籍
当你说出 promise.all
和 promise.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)
})
复制代码
//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);
复制代码
Promise 必知必会(十道题): 有助于你更加深入的了解 promise 的运行状况
更多的Promise 详情能够参考JavaScript Promise迷你书(中文版);