ユーザ用ツール

サイト用ツール


サイドバー

javascript:class

class

javascriptには厳密な型がない。そのためinterfaceはないが、interfaceっぽいことは簡単にできる。

Anmimal.js
export class Animal{
    constructor(name){
        this.name = name
    }
    cry(){
        return "cry!"
    }
}
 
export class Cat extends Animal{
    constructor(name){
        super(name)
    }
    cry(){
        return "nyaa"
    }
}
 
export class Dog extends Animal{
    constructor(name){
        super(name)
    }
    cry(){
        return "bau"
    }
}
Human.js
export default class Human{
    constructor(pet){
        this.pet = pet
    }
    doCry(){
        return this.pet
    }
}
Animal.test.js
import {Animal,Cat,Dog} from '../Animal'
import Human from '../Human'
 
describe("Extends",()=>{
 
    test("Animal",()=>{
        let a = new Animal()
        expect(a.cry()).toBe("cry!")
    })
 
    test("Cat",()=>{
        let a = new Cat("tama")
        expect(a.cry()).toBe("nyaa")
    })
 
    test("Pet",()=>{
        // Humanはpetというメンバ変数を持っている。
        // pet(という型はない)にAnimalを継承したCatを設定しCatのメソッドを呼び出している。
        let minako = new Human(new Cat("tama"))
        expect(minako.doCry().cry()).toBe("nyaa")
 
    })
 
})
javascript/class.txt · 最終更新: 2019/03/05 23:55 by ips