1 let const
1.1 let
let 聲明的變量是在其塊級作用域起作用,與 var 相似。二者之間最主要的區(qū)別在于 var 聲明的變量的作用域是整個封閉函數(shù)洲敢。
示例1:let 對比 var
var a = 5;
var b = 10;
if (a === 5) {
let a = 4; // a 作用域是 if 代碼塊內(nèi)败玉;
var b = 1; // b 作用域是 整個函數(shù);
console.log(a); // 4
console.log(b); // 1
}
console.log(a); // 5
console.log(b); // 1
let的作用域是塊疫铜,而var的作用域是函數(shù)
示例2:let 在循環(huán)中
for (let i = 0; i < 10; i++) {
console.log(i); // 0, 1, 2, 3, 4 ... 9
}
console.log(i); // i is not defined
可以用 let 來代替 var 茂浮,在 for 定義塊中使用塊級變量.
1.2 const
const 是用來聲明常用的,常量的值不能通過重新賦值來改變壳咕,并且不能重新聲明货矮。
const number = 42;
try {
number = 99;
} catch(err) {
console.log(err); // TypeError: Assignment to constant variable.
}
console.log(number); // 42
2 字符串模板
以前的寫法:
$("#content").append(
"我是" + obj.name + "</b> " +
"的爸爸, " +
"今年" + obj.age + "歲!"
);
我們要用一堆的'+'號來連接文本與變量,而使用ES6的新特性模板字符串``(頓號)后份蝴,我們可以直接這么來寫:
$("#content").append(`
我是${obj.name}
的爸爸,
今年${obj.age}歲!
`);
使用用${}來引用變量六剥,而且所有的空格和縮進(jìn)都會被保留輸出。
3 箭頭函數(shù)
3.1 箭頭函數(shù)與普通函數(shù)對比:
function show(a) { return a } ;
對應(yīng)箭頭函數(shù)寫法:
let show = a => a;
function show(a,b) { return a+b } ;
對應(yīng)箭頭函數(shù)寫法:
let show = (a, b) => a+b;
function show() { return 'welcome' } ;
對應(yīng)箭頭函數(shù)寫法:
let show = () => 'welcome';
function show() { alert(1); return 'hi' } ;
對應(yīng)箭頭函數(shù)寫法:
let show = () => { alert(1); return 'hi' };
3.2 this 說明
// 沒有獨立作用域
let obj = {
commonFn: function () {
console.log(this); // 普通函數(shù)庞呕,this指向調(diào)用函數(shù)新翎。
},
arrowFn: () => {
console.log(this); // 箭頭函數(shù),沒有獨立作用域住练,與 obj 所在的作用域相同地啰。
}
}
obj.commonFn(); // this 指向 obj 作用域;
obj.arrowFn(); // this 指向 obj 所在作用域讲逛,window亏吝。
4 Promise
- 就是一個對象,用來傳遞和處理異步操作的數(shù)據(jù)
- 狀態(tài):
pending(等待) → Resolve(成功)
→ Reject(失斦祷臁)
promise 的狀態(tài)只能從 pending 到 resolve蔚鸥,或者從 pending 到reject。
4.1 Promise常見結(jié)構(gòu)
new Promise((resolve, reject) => {
$.ajax({
url: 'xxx',
type: 'post',
success: (result) => {
resolve(result);
},
error: (err) => {
reject(err);
}
});
}).then((result) => {
console.log("成功", result);
}, (err) => {
console.log("失敗", err);
});
4.2 promise鏈?zhǔn)秸{(diào)用
let promiseFn1 = new Promise((resolve, reject) => {
$.ajax({
url: 'xxx',
type: 'post',
success: (result) => {
resolve(result);
},
error: (err) => {
reject(err);
}
});
});
let promiseFn2 = new Promise((resolve, reject) => {
$.ajax({
url: 'xxx',
type: 'post',
success: (result) => {
resolve(result);
},
error: (err) => {
reject(err);
}
});
});
promiseFn1.then((result) => {
console.log("promiseFn1 成功被調(diào)用", result);
return promiseFn2; // 這里返回的是第二個 promiseFn2 P碓摺V古纭!
}).then((result) => {
console.log("promiseFn2 成功被調(diào)用");
});
4.3 promise使用
4.3.1 then
then基礎(chǔ)用法:
var p1 = new Promise(function (resolve, reject) {
resolve('1');
// reject('2');
});
p1.then(function (val) {
alert('resolve混聊,成功調(diào)用函數(shù)' + val);
}, function (val) {
alert('reject弹谁,失敗調(diào)用函數(shù)' + val);
});
then 鏈?zhǔn)秸{(diào)用:
var p1 = new Promise(function (resolve, reject) {
resolve(1);
});
p1.then(function (val) {
console.log(val); // 1
return val + 1; // 這里返回的值,給下一次then調(diào)用
}, function (val) {
alert('reject句喜,失敗調(diào)用函數(shù)' + val);
}).then(function (value) { // then鏈?zhǔn)秸{(diào)用
console.log(value); // 2
})
then ajax的應(yīng)用:重要的是思想
function ajax(url, fnSucc, fnFail) {
let oAjax = new XMLHttpRequest();
oAjax.open('GET', url, true);
oAjax.send();
oAjax.onload = function () {
if (oAjax.readyState == 4 && oAjax.status == 200) {
fnSucc(oAjax.responseText);
} else {
fnFail(oAjax.status);
}
}
}
let p1 = new Promise(function (resolve, reject) {
ajax("url", function (result) { // 進(jìn)行ajax的調(diào)用
resolve(result);
}, function (result) {
reject(result);
})
});
p1.then(function (val) {
console.log('成功' + val);
}, function (val) {
console.log('失敗' + val);
});
4.3.2 catch(用來捕獲錯誤)
var p1 = new Promise(function (resolve, reject) {
resolve('成功了');
});
p1.then(function (val) {
console.log(val); // 成功了
throw '發(fā)生錯誤了';
}).catch(function (e) {
console.log(e); // 發(fā)生錯誤了
});
4.3.3 all
用于將多個promise對象预愤,組合、包裝成一個全新的promise對象咳胃。
Promise.all([p1, p2, p3...])植康;所有的promise成功了,才能算是成功展懈,否則向图,只要有一個失敗了泳秀,就是失敗。
var p1 = Promise.resolve(1); // resolve 成功
var p2 = Promise.reject(2); // reject 失敗
Promise.all([true, p1]).then(function (val) {
console.log(val); // 輸出: 數(shù)組 [true, 1]
}, function (val) {
console.log("失敗了" + val);
});
Promise.all([true, p1, p2]).then(function (val) {
console.log("成功了" + val);
}, function (val) {
console.log("失敗了" + val); // 輸出: 失敗了2
});
4.3.4 race
哪個promise先返回榄攀,就使用哪個
var p1 = new Promise(function (resolve, reject) {
setTimeout(() => {
resolve('one');
}, 500);
});
var p2 = new Promise(function (resolve, reject) {
setTimeout(() => {
resolve('two');
}, 100);
});
Promise.race([p1, p2]).then(function (val) {
console.log("成功了" + val); // 成功了two
});
4.3.5 reject
Promise.reject() -- 生成一個錯誤的promise
4.3.6 resolve
Promise.resolve() -- 生成一個成功的promise
5 對象
5.1 對象字面量的定義寫法
5.1.1 es5 定義對象字面量的寫法:
var name = "xiaoming",
age = 1;
var obj = {
name: name,
age: 2,
getName: function () {
return this.name;
},
getAge: function () {
return this.age;
}
}
console.log(obj.getName()); // 小明
console.log(obj.getAge()); // 2
5.1.2 es6 定義對象字面量的寫法
let name = "xiaoming",
age = 1;
let obj = {
name, // 變量名可以直接使用對象的屬性名稱
age: 2,
getName() { // 對象里的方法可以簡寫
return this.name;
},
getAge() {
return this.age;
}
}
console.log(obj.getName()); // xiaoming
console.log(obj.getAge()); // 2
5.2 單例模式:json key--value 簡寫
var name = 'abc';
var age = 11;
var person = {
name,
age,
showName: () => {
alert(this.name); // 輸出:abc
},
showAge: () => {
alert(this.age);
}
}
person.showName(); // 箭頭函數(shù) this 指向跟 person 同級的作用域嗜傅, window
5.3 面向?qū)ο?/h3>
5.3.1原型繼承寫法
// 又是類,又是構(gòu)造函數(shù)
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.showName = function () {
return this.name;
}
Person.prototype.showAge = function () {
return this.age;
}
// (原型)繼承 子類.prototype = new 父類()
function Worker(name, age) {
Person.apply(this, arguments);
}
Worker.prototype = new Person(); // 子類.prototype = new 父類()
var p = new Person('abc', 11);
alert(p.showAge()); // 11
var w = new Worker('abcd', 191);
alert(w.showAge()); // 191
// 又是類,又是構(gòu)造函數(shù)
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.showName = function () {
return this.name;
}
Person.prototype.showAge = function () {
return this.age;
}
// (原型)繼承 子類.prototype = new 父類()
function Worker(name, age) {
Person.apply(this, arguments);
}
Worker.prototype = new Person(); // 子類.prototype = new 父類()
var p = new Person('abc', 11);
alert(p.showAge()); // 11
var w = new Worker('abcd', 191);
alert(w.showAge()); // 191
(原型)繼承 子類.prototype = new 父類();
5.3.2 類和構(gòu)造函數(shù)
class Person { // 類
constructor(name, age) { //構(gòu)造函數(shù)
this.name = name;
this.age = age;
}
showName() {
return this.name;
}
showAge() {
return this.age;
}
}
var p = new Person('abc', 121);
alert(p.showAge()); //121
5.3.3 繼承
// 父類
class Person { // 類
constructor(name, age) { //構(gòu)造函數(shù)
this.name = name;
this.age = age;
}
showName() {
return this.name;
}
showAge() {
return this.age;
}
}
var p = new Person('abc', 121);
alert(p.showAge()); //121
// 繼承檩赢,子類繼承父類
class Worker extends Person {
constructor(name, age, job = '賣報') { // 默認(rèn)值
super(name, age); // 調(diào)用父類的構(gòu)造函數(shù)
this.job = job;
}
showJob() {
return this.job;
}
}
var w = new Worker('abc', 11);
alert(w.showAge()); // 11
alert(w.showJob()); // 賣報
5.3.4 對象應(yīng)用舉例
// 模擬隊列
class Queue {
constructor(content = []) {
this._queue = [...content];
}
shift() {
var val = this._queue[0];
this._queue.shift(); // 這個才是重要的吕嘀,模仿刪除第一個元素
return val; // 返回刪除的元素值
}
push(n) {
this._queue.push(n); // 這個才是重要的
return this._queue.length; // 返回新增后數(shù)組長度
}
}
let q = new Queue([1, 2, 3, 4]);
q.shift();
q.push(5);
console.log(q._queue);
6 ES6模塊化
以前:seajs、requirejs
6.1 如何定義導(dǎo)出贞瞒、導(dǎo)入模塊
6.1.1 導(dǎo)出模塊
// aa.js
const a = 11;
export default a
6.1.2 導(dǎo)入模塊
// bb.js:
import modA from './aa.js'
alert(modA) // 11
導(dǎo)入和導(dǎo)出模塊使用 export 和 import 關(guān)鍵字偶房。
6.2 導(dǎo)出導(dǎo)入函數(shù)
// aa.js
const a = 12;
export default a;
// bb.js
const b = 2;
export default b;
// s_sum.js
import modA from './aa.js';
import modB from './bb.js';
export default function s_sum() {
return modA + modB;
};
// index.js
import sumMod from './s_sum';
alert(sumMod()); // 導(dǎo)出來的模塊是函數(shù)
6.3 導(dǎo)出、導(dǎo)入多個模塊
6.3.1 導(dǎo)出多個模塊
// aa.js:使用對象導(dǎo)出多個模塊
const a = 12;
const b = 13;
export default {a, b}
6.3.2 導(dǎo)入多個模塊
// bb.js:引用
import c from './aa.js';
var a = c.a;
var b = c.b;
6.4 默認(rèn)導(dǎo)出军浆、導(dǎo)入模塊
6.4.1 對比使用命名導(dǎo)出
6.4.1.1 使用命名導(dǎo)出
// module "my-module.js"
function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
var graph = {
options: {
color:'white',
thickness:'2px'
},
draw: function() {
console.log('From graph draw function');
}
}
export { cube, foo, graph };
6.4.1.2 使用命名導(dǎo)入
import { cube, foo, graph } from 'my-module';
graph.options = {
color: 'blue',
thickness: '3px'
};
graph.draw();
console.log(cube(3)); // 27
console.log(foo); // 4.555806215962888
6.4.2 默認(rèn)導(dǎo)出棕洋、導(dǎo)入
6.4.2.1 默認(rèn)導(dǎo)出
// module "my-module.js"
export default function cube(x) {
return x * x * x;
}
6.4.2.2 默認(rèn)導(dǎo)入
// module "my-module.js"
import cube from 'my-module';
console.log(cube(3)); // 27?????
說明:
import a, {b, c} from mode;
- 不用大括號包起來的導(dǎo)入模塊 a,表示是 mode 中用 export default a 導(dǎo)出的默認(rèn)模塊乒融;
- b掰盘、c 是 export 導(dǎo)出的模塊,不是默認(rèn)mode中的默認(rèn)模塊赞季。
7 常見知識點
7.1 超鏈接(三個點...)應(yīng)用
function show(...args) {
args.push(4);
console.log(args);
}
show(1, 2, 3);
7.2 解構(gòu)和釋構(gòu)
const data = [...this.state.gData];
等同于:
const { gData } = this.state;
const data = [...gData];
如果你理解上面代碼的意思愧捕,那解構(gòu)和釋構(gòu)基本就算過關(guān)了。
7.3 循環(huán)嵌套
let values = [1, 2, 3];
let str = `<ul>${values.map(value => `<li>值為:${value}</li>`).join('')}</ul>`
console.log(str);
7.4 復(fù)制數(shù)組
7.4.1 for循環(huán)
let arr = [1, 2, 3];
let arr2 = [];
for (let i = 0; i < arr.length; i++) {
arr2[i] = arr[i]
}
console.log(arr, arr2);
arr2.pop();
console.log(arr, arr2);
console.log(arr === arr2);
7.4.2 Array.from(arr)
let arr = [1, 2, 3];
let arr2 = Array.from(arr);
console.log(arr, arr2);
arr2.pop();
console.log(arr, arr2);
console.log(arr === arr2);
7.4.3 超鏈接(三個點...)
let arr = [1, 2, 3];
let arr2 = [...arr];
console.log(arr, arr2);
arr2.pop();
console.log(arr, arr2);
console.log(arr === arr2);
7.5 循環(huán)
7.5.1 普通 for
let arr = ['apple', 'bannel', 'cat'];
for (let i in arr) {
console.log(i); // 0, 1, 2 索引
}
7.5.2 for in
// 數(shù)組:
let arr = ['apple', 'bannel', 'cat'];
for (let i in arr) {
console.log(i); // 0, 1, 2 索引
}
// json
var json = { 'a': 'apple', 'b': 'bannel', 'c': 'cat' };
for (let i in json) {
console.log(i); // a, b, c 索引
}
7.5.3 for of
let arr = ['apple', 'bannel', 'cat'];
for (let i of arr) {
console.log(i); // 'apple', 'bannel', 'cat' 值
}
for of 可以循環(huán)數(shù)組申钩,但是不能循環(huán) json 對象次绘,其真正的用途是用于循環(huán) map 對象。
7.6 Map 對象
和 json 相似撒遣,也是一種key-value形式邮偎,Map對象為了和for of 循環(huán)配合而生的。
7.6.1 Map對象創(chuàng)建义黎、設(shè)置钢猛、獲取和刪除操作
// 創(chuàng)建Map對象
var map = new Map();
// 設(shè)置值
map.set('a', 'apple');
map.set('b', 'bannel');
map.set('c', 'cat');
// 獲取值
map.get('a');
// 刪除
map.delete('a');
console.log(map);
7.6.2 map 配合 for of
7.6.2.1 方式一
Map 對象
// map 配合 for of
var map = new Map();
// 設(shè)置值
map.set('a', 'apple');
map.set('b', 'bannel');
map.set('c', 'cat');
for (let name of map) {
console.log(name);
}
7.6.2.2 方式二
Map 對象
var map = new Map();
// 設(shè)置值
map.set('a', 'apple');
map.set('b', 'bannel');
map.set('c', 'cat');
for (let name of map.entries()) {
console.log(name);
}
7.6.2.3 方式三
key - value
var map = new Map();
// 設(shè)置值
map.set('a', 'apple');
map.set('b', 'bannel');
map.set('c', 'cat');
for (let [key, val] of map) {
console.log(key, val);
}
7.6.2.4 方式四
獲取 key
var map = new Map();
// 設(shè)置值
map.set('a', 'apple');
map.set('b', 'bannel');
map.set('c', 'cat');
for (let k of map.keys()) { // a,b,c -- key
console.log(k);
}
7.6.2.5 方式五
獲取 value
var map = new Map();
// 設(shè)置值
map.set('a', 'apple');
map.set('b', 'bannel');
map.set('c', 'cat');
for (let val of map.values()) { // value
console.log(val);
}
8 簡單總結(jié)
- 基礎(chǔ)指令:let、const轩缤;
- 字符串模板:'${name}xxx';
- 箭頭函數(shù):value => return value + 1贩绕;
- promise
- 面向?qū)ο螅篶lass火的、extends、super淑倾、constructor
- 模塊化:export馏鹤、import、as娇哆、default