1. JavaScript 計算屬性 computed property
(1). ES6允許我們在方括號 [] 中,使用一個表達式。然後,將使用表達式的結果作爲一個對象的屬性名稱。
如:let name = 'animal name';
let animal = {
[name]: 'cat',
age: 3
};
console.log(animal['animal name']); // 'cat'
// [name] 就是animal對象的一個計算屬性
- 類的getter和setters也可以使用計算屬性
如:let greeting = 'sayHi';
class Cat {
constructor(name, age){
this.name = name;
this.age = age;};
get [greeting] () { return `Hi, I'm ${this.name}. I'm ${this.age} years old.` };
};
let cat = new Cat('lulu', 3);
console.log(cat.sayHi); // 'Hi, I'm lulu. I'm 3 years old.'
2. Extends 與 Super 關鍵詞
(1). ES6通過使用extends與super關鍵詞,簡化了實現繼承的步驟
- 在ES6之前,JavaScript使用原型繼承技術。
如:function Animal (name, food) {
this.name = name;
this.food = food;
};
Animal.prototype.eat = function () { console.log(this.name + ' eat ' + this.food); };
function Cat (name, food) { Animal.call(this, name, food);};
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Animal;
Cat.prototype.sound = function () { console.log('miao...'); };
let cat = new Cat('lulu', 'fish');
cat.eat(); // 'lulu eat fish'
cat.sound(); // 'miao...'
- 使用extends與super關鍵詞后,步驟簡化了。
如:class Animal {
constructor(name, food) {
this.name = name;
this.food = food;};
eat(){ console.log(this.name + ' eat ' + this.food); };
static greeting(){ console.log('Hi, there.'); };
};
class Cat extends Animal {
constructor(name, food) { super(name, food); }; // 有子構造器就必須調用super(), 否則報錯
// 如果不寫子構造器,那麽系統會默認為等同於父構造器
// super(name, food) 等同於 Animal.call(this,name,food)
sound(){ console.log('miao...'); };
};
let cat = new Cat('Lulu', 'fish');
cat.eat(); // 'lulu eat fish'
cat.sound(); // 'miao...'
(2). 影子方法 shadowing methods
- 如果子方法與父方法同名,那麽調用的會是子方法。如果想要調用父方法,則需要使用super.方法名(參數)。
如:class Cat extends Animal {
eat() {
super.eat();
console.log('Cat like fish.');
};
sound(){ console.log('miao...'); };
};
let cat = new Cat('xixi', 'mouse');
cat.eat(); // 'xixi eat mouse' 'Cat like fish.'
(3). 繼承靜態成員
- 子類可以繼承父類的所有靜態方法。
如:Cat.greeting(); // 'Hi, there.'
(4). 繼承内置類型 built-in types
- JavaScript允許我們通過繼承來擴展一個内置類型(如:Array, String, Map和Set)。
如:class Necklace extends Array {
addBead(b) { super.push(b); };
removeBead() { return super.shift(); };
empty() { return this.length === 0; };
};
let beads = new Necklace();
beads.addBead(1);
beads.addBead(1);
console.log(beads.length); // 2