Featured image of post 【JavaScript 变数】变数类型介绍:Class 类别

【JavaScript 变数】变数类型介绍:Class 类别

【JavaScript 变数】变数类型介绍:Class 类别

Photo by Mohammad Rahmani on Unsplash

函式方法

变数 说明
constructor 建构子
super 上层类别
instanceof 判断是类为指定类别

建立类别

class Animal {
    constructor(name, color){
        this.name = name
        this.color = color
    }
    sayHi(){
        console.log(`[Animal] My name is「${this.name}」 My color is 「${this.color}」`);
    }
}
const animal = new Animal('Dog','white');

// [Animal] My name is「Dog」 My color is 「white」
animal.sayHi()

继承类别

class Cat extends Animal {
    sayHi() {
        console.log(`[Cat] My name is「${this.name}」 My color is 「${this.color}」`);
    }
}
const KittyCat = new Cat('Kitty', 'pink');
// [Cat] My name is「Kitty」 My color is 「pink」
KittyCat.sayHi();

呼叫父类别方法

class Cat extends Animal {
    sayHi() {
        console.log(`[Cat] My name is「${this.name}」 My color is 「${this.color}」`);
        super.sayHi();
    }
}

const KittyCat = new Cat('Kitty', 'pink')
// [Cat] My name is「Kitty」 My color is 「pink」
// [Animal] My name is「Kitty」 My color is 「pink」
KittyCat.sayHi();

判断是类为指定类别

console.log(KittyCat instanceof Cat) // true

console.log(KittyCat instanceof Animal) // true

Reference

Donate KJ 贊助作者喝咖啡

如果這篇文章對你有幫助的話,可以透過下面支付方式贊助作者喝咖啡,如果有什麼建議或想說的話可以贊助並留言給我
If this article has been helpful to you, you can support the author by treating them to a coffee through the payment options below. If you have any suggestions or comments, feel free to sponsor and leave a message for me!
方式 Method 贊助 Donate
PayPal https://paypal.me/kejyun
綠界 ECPay https://p.ecpay.com.tw/AC218F1
歐付寶 OPay https://payment.opay.tw/Broadcaster/Donate/BD2BD896029F2155041C8C8FAED3A6F8
All rights reserved,未經允許不得隨意轉載
Built with Hugo
主题 StackJimmy 设计