ES6 語法
- let / var
- const 的使用
- class、extends、super
- 箭頭函式(arrow function)
- 模版字串(template string)
- 結構(destructuring)
- default、rest
- ES6 module
- import、export
- 其他語法
- Promise
- 參考
不定時更新,慢慢積累…
let / var
事實上 var 的設計可以看成 JavaScript 語言設計上的錯誤,這種錯誤多半不能修復和移除,因為需要向后兼容
- 大概十年前,Brendan Eich 就決定修復這個問題,于是他添加了一個新的關鍵字 let
- 我們可以將 let 看成更完美的 var
塊級作用域:
- JS 中使用 var 來宣告一個變數時,變數的作用域主要是和函式的定義有關
- 針對于其他塊定義來說是沒有作用域的,比如 if / for 等,這在開發中往往會引起一些問題
以前解決 塊級作用域 問題的方法:
var btns = document.getElementsByTagName('button');
for (var i=0; i<btns.length; i++) {
(function (num) { // 0
btns[i].addEventListener('click', function () {
console.log('第' + num + '個按鈕被點擊');
})
})(i)
}
ES6 解決 塊級作用域 問題的方法:
const btns = document.getElementsByTagName('button')
for (let i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function () {
console.log('第' + i + '個按鈕被點擊');
})
}
const 的使用
在很多語言中已經存在,比如 C/C++ 中,主要的作用是將某個變數修飾為常量
在 JavaScript 中也是如此,使用 const 修飾的識別符號為常量,不可以再次賦值
什么時候使用 const 呢?
- 當我們修飾的識別符號不會被再次賦值時,就可以使用 const 來保證資料的安全性
建議:在 ES6 開發中,優先使用 const,只有需要改變某一個識別符號的時候才使用 let
const 注意點:
- const 注意一:const 修飾的變數不可修改值
const a = 20; a = 30; // 錯誤,不可以修改 - const 注意二:const 修飾的變數必須賦初值
const name; // 錯誤,cons修飾的變數必須賦初值
const 有一個很好的應用場景,就是當我們參考第三方庫時宣告的變數,用 const 來宣告可以避免未來不小心重命名而導致出現 bug:
const monent = require('moment')
class、extends、super
ES6 提供了更接近傳統語言的寫法,引入了 Class(類)這個概念,新的 class 寫法讓物件原型的寫法更加清晰、更像面向物件編程的語法,也更加通俗易懂,
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)
ES6 最常用的特性之一,用它寫 function 比原來的寫法簡潔清晰很多,
function(i){
return i + 1;
} //ES5
i => i + 1 //ES6 或一個引數時省略為 i=>i+1
如果函式比較復雜,則需要用 {} 把代碼包起來:
function(x, y) {
x++;
y--;
return x + y;
}
(x, y) => {
x++;
y--;
return x+y
}
JavaScript 語言的 this 物件一直是一個令人頭痛的問題,在物件方法中使用 this,必須非常小心:
class Animal {
constructor(){
this.type = 'animal'
}
says(say){
setTimeout(function(){
console.log(this.type + ' says ' + say)
}, 1000)
}
}
var animal = new Animal()
animal.says('hi') //undefined says hi
運行上面的代碼會報錯,這是因為 setTimeout 中的 this 指向的是全域物件(閉包中的未定義變數,默認指向全域作用域),所以為了讓它能夠正確的運行,傳統的解決方法有兩種:
- 將 this 傳給 self,再用 self 來指代 this
says(say){
var self = this;
setTimeout(function(){
console.log(self.type + ' says ' + say)
}, 1000)
- 使用
bind(this)
says(say){
setTimeout(function(){
console.log(this.type + ' says ' + say)
}.bind(this), 1000)
現在有了箭頭函式,就不需要這么麻煩了:
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 就是外層代碼塊的this,
模版字串(template string)
傳統的使用 + 和 " 字串拼接:
$("#result").append(
"There are <b>" + basket.count + "</b> " +
"items in your basket, " +
"<em>" + basket.onSale +
"</em> are on sale!"
ES6 的新特性模板字串:使用 ${} 來參考變數
$("#result").append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);
結構(destructuring)
ES6 允許按照一定模式,從陣列和物件中提取值,對變數進行賦值,這被稱為 解構
ES5 的寫法:
let cat = 'ken'
let dog = 'lili'
let zoo = {cat: cat, dog: dog}
console.log(zoo) //Object {cat: "ken", dog: "lili"}
ES6 :屬性簡寫
let cat = 'ken'
let dog = 'lili'
let zoo = {cat, dog}
console.log(zoo) //Object {cat: "ken", dog: "lili"}
ES6:解構賦值
let dog = {type: 'animal', many: 2}
let { type, many} = dog //import { validateUserName } from '@/utils/validate'
console.log(type, many) //animal 2
default、rest
ES5 指定默認值:
function animal(type){
type = type || 'cat'
console.log(type)
}
animal()
ES6 指定默認值:
function animal(type = 'cat'){
console.log(type)
}
animal()
ES6 的 rest 語法:
function animals(...types){
console.log(types)
}
animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]
如果不用 ES6 的話,我們則得使用 ES5 的 arguments
ES6 module
import、export
ES6 之前為解決 JavaScript 的模塊化問題,常常利用一些第三方方案,主要有 CommonJS(服務器端)、AMD(瀏覽器端,如 require.js)
ES6 的 module 實作非常簡單,可以成為服務器和瀏覽器通用的模塊解決方案,
require.js 解決方案:
//content.js
define('content.js', function(){
return 'A cat';
})
//index.js
require(['./content.js'], function(animal){
console.log(animal); //A cat
})
CommonJS 解決方案:
//index.js
var animal = require('./content.js')
//content.js
module.exports = 'A cat'
ES6 的寫法:
//index.js
import animal from './content'
//content.js
export default 'A cat'
其他語法
export 命令除了輸出變數,還可以輸出函式,甚至是類:
//content.js
export default 'A cat'
export function say(){
return 'Hello!'
}
export const type = 'dog'
import:大括號里面的變數名,必須與被匯入模塊(content.js)對外介面的名稱相同
- 如果還希望輸入 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
ES6 中可以用 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
ES6 用 * 實作模塊的整體加載(將所有輸出值加載到一個物件上)且可以和 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
Promise
參考 【Vue.js 知識量化】Promise
參考
- 30分鐘掌握ES6/ES2015核心內容
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/289614.html
標籤:其他
上一篇:2021暑假第三次討論班
