JavaScript 自學筆記22

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值