ES6學習(模塊化)
大家都知道js不支持模塊化,像ruby有require,python有import
在ES6出現之前,社區也制定了一套模塊規範,
CommonJS require(‘http’) 還有AMD,CMD等其他規範
ES6出現後,一統服務端和客戶端的模塊規範
我們這樣定義和使用模塊(注意要在localhost)
export const a = 10;
export {
temp as t,
a as num
}
<script type="module">
import './modules/1.js';
import {t as temp, num as i_num} from './modules/2.js'
import * as modTwo from './modules/2.js';
</script>
像這樣引入是不可以加入代碼邏輯的,如果想使用代碼邏輯來引入js,例如條件判斷,這時候我們要選擇import(),它返回一個promise對象
import('./common.js').then(res=>{
console.log(res.a)
})
類
想想我們之前在js中是怎樣定義類的,其實就是定義方法
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.showName = function(){
return `名字爲 ${this.name}`
}
let p = new Person('Peter',18);
console.log(p.showName());
ES6是怎麼寫的呢?
<script>
class Person {
constructor(name,age){
this.name = name;
console.log(name,age)
}
}
showName(){
console.log(this.name)
}
let p = new Person('Peter',21);
</script>
其實本質還是function,我們可以typeof 出來
下面我們介紹一下get,set
<script>
class Person {
constructor(name,age){
console.log(name,age)
}
set test(val){
alert(val)
}
get test(){
return 'get'
}
}
let p = new Person('Peter',21);
p.test = "666"
console.log(p.test)
</script>
平時我也很少用到,大家作爲了解,
繼承
說到類,就不得不提到繼承
----- 如果用以前的方法,就不得不設置this
矯正this:
1. fn.call(this指向誰, args1, args2…)
2. fn.apply(this指向誰, [args1, args2…])
3. fn.bind()
到了ES6,簡直是不要再輕鬆----- extends 和java一樣
在子類的構造函數中不要忘記調用super()
下一次寫個拖拽的小栗子