在ES2015之前,定義類的方法只能通過原型鏈來模擬
function Animal(family,species) { this.family = family; this.species = species; }; Animal.prototype.yell = function() { console.log(this.family); } let dog = Animal('dogs','four feet');
而在ES2015中可以使用class關鍵字來定義類,使用constructor來定義類創建時所需的參數,直接定義函數來創建類方法:
class Animal { constructor (family,species) { this.family = family; this.species = species; }; yell () {// 等於Animal.prototype.yell = function(){} return this.family; } } const dog = new Animal('dog','four feet');
在類定義中可以看到yell的方法沒有使用鍵值對的方式,這也是ES6中新引入的對象字面量擴展,等同於:
const Animal= { yell: function() { return this.family; } }
類 + promise
class Point { constructor (x, y) { this.x = x; this.y = y; }; moveright(step) { return new Promise(resolve => resolve({ x: this.x + step, y: this.y })) } } const p = new Point(2,5);
定義一個點類,擁有moveright的方法,返回的使一個Promise,利用箭頭函數調用resolve,使Promise狀態轉換到onFulfilled。
p.moveright(3)
.then(({x, y}) => console.log(`${x}, ${y}`));//5,5
這里的{x,y} 用了ES6的新語法解構,將返回的對象中的x和y鍵對應的值返回。
下面講講類的繼承,在函數中的繼承有很多種繼承方式,具體的繼承方式我會在我的博客中更新。
創建一個Point2D類
class Point2D { constructor(x,y) { this.x = x; this.y = y; } toString() { console.log('2d function'); return `${this.x},${this.y}`; } };
創建Point3D類並繼承Point2D,核心關鍵字extends, super
class Point3D extends Point2D { constructor(x,y,z) { super(x,y);// 如果沒有super,則在constructor中不能使用this,其他方法中可以。 this.z = z; } toString(){ super.toString(); return `${this.x},${this.y},${this.z}`; } };
這樣的繼承方式比使用function繼承來的更為直接和方便。
最后測試:
const p = new Point3D(1,2,3) p.toString()
輸出為:
這樣使用super便實現了對父類方法的繼承。