1.基本語法
JavaScript 語言中蚓胸,生成實(shí)例對(duì)象的傳統(tǒng)方法是通過構(gòu)造函數(shù)。
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 2);
ES6引入了Class(類)的概念來實(shí)現(xiàn)構(gòu)造函數(shù)口锭。ES6 的class可以看作只是一個(gè)語法糖杨拐,它的絕大部分功能糊肠,ES5 都可以做到,新的class寫法只是讓對(duì)象原型的寫法更加清晰悯辙、更像面向?qū)ο缶幊痰恼Z法而已琳省。上面的代碼用 ES6 的class改寫,就是下面這樣
//定義類
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var p=new Point(1,2)
1.constructor方法躲撰,這就是構(gòu)造函數(shù)的寫法
2.定義“類”的方法的時(shí)候针贬,前面不需要加上function這個(gè)關(guān)鍵字,直接把函數(shù)定義放進(jìn)去了就可以
3.方法之間不需要逗號(hào)分隔拢蛋,加了會(huì)報(bào)錯(cuò)
上面代碼定義了一個(gè)“類”坚踩,可以看到里面有一個(gè)constructor方法,這就是構(gòu)造函數(shù)的寫法瓤狐,而this關(guān)鍵字則代表實(shí)例對(duì)象p瞬铸。
Point類除了構(gòu)造方法,還定義了一個(gè)toString方法础锐。注意嗓节,定義“類”的方法的時(shí)候,前面不需要加上function這個(gè)關(guān)鍵字皆警,直接把函數(shù)定義放進(jìn)去了就可以了拦宣。另外,方法之間不需要逗號(hào)分隔,加了會(huì)報(bào)錯(cuò)鸵隧。
2.constructor方法
一個(gè)類必須有constructor方法绸罗,如果沒有顯式定義,一個(gè)空的constructor方法會(huì)被默認(rèn)添加
constructor方法是類的默認(rèn)方法豆瘫,通過new命令生成對(duì)象實(shí)例時(shí)珊蟀,自動(dòng)調(diào)用該方法。一個(gè)類必須有constructor方法外驱,如果沒有顯式定義育灸,一個(gè)空的constructor方法會(huì)被默認(rèn)添加。
class Point {
}
// 等同于
class Point {
constructor() {}
}
3.類的實(shí)例對(duì)象
生成類的實(shí)例對(duì)象的寫法昵宇,與 ES5 完全一樣磅崭,也是使用new命令
class Point {
// ...
}
// 實(shí)例
var point = new Point(2, 3);
4.類的繼承
Class 可以通過extends關(guān)鍵字實(shí)現(xiàn)繼承,這比 ES5 的通過修改原型鏈實(shí)現(xiàn)繼承瓦哎,要清晰和方便很多
class Point {
}
class ColorPoint extends Point {
}
上面代碼定義了一個(gè)ColorPoint類砸喻,該類通過extends關(guān)鍵字,繼承了Point類的所有屬性和方法蒋譬。但是由于沒有部署任何代碼恩够,所以這兩個(gè)類完全一樣,等于復(fù)制了一個(gè)Point類羡铲。
子類必須在constructor方法中調(diào)用super方法蜂桶,否則新建實(shí)例時(shí)會(huì)報(bào)錯(cuò)
子類必須在constructor方法中調(diào)用super方法,否則新建實(shí)例時(shí)會(huì)報(bào)錯(cuò)也切。這是因?yàn)樽宇悰]有自己的this對(duì)象扑媚,而是繼承父類的this對(duì)象。如果不調(diào)用super方法雷恃,子類就得不到this對(duì)象疆股。
class Point { /* ... */ }
class ColorPoint extends Point {
constructor() {
}
}
let cp = new ColorPoint(); // ReferenceError
如果子類沒有定義constructor方法,這個(gè)方法會(huì)被默認(rèn)添加
class ColorPoint extends Point {
}
// 等同于
class ColorPoint extends Point {
constructor() {
super();
}
}
5.super關(guān)鍵字
super作為函數(shù)調(diào)用時(shí)倒槐,代表父類的構(gòu)造函數(shù)
ES6 要求旬痹,子類的構(gòu)造函數(shù)必須執(zhí)行一次super函數(shù),否則 JavaScript 引擎會(huì)報(bào)錯(cuò)
super雖然代表了父類的構(gòu)造函數(shù),但是返回的是子類的實(shí)例讨越,即super內(nèi)部的this指的是子類的實(shí)例
class A {
constructor() {
console.log(new.target.name);
}
}
class B extends A {
constructor() {
super();
}
}
new A() // A
new B() // B
作為函數(shù)時(shí)两残,super()只能用在子類的構(gòu)造函數(shù)之中,用在其他地方就會(huì)報(bào)錯(cuò)把跨。
class A {}
class B extends A {
m() {
super(); // 報(bào)錯(cuò)
}
}