zoukankan      html  css  js  c++  java
  • 5.class

    一、 类

    class Greeter {
        greeting: string;
        constructor(message: string) {
            this.greeting = message;
        }
        greet() {
            return "Hello, " + this.greeting;
        }
    }
    
    let greeter = new Greeter("world");
    console.log(greeter.greet())

    构造方法是 constructor

    二、继承

    class Animal {
        move(distanceInMeters: number = 0) {
            console.log(`Animal moved ${distanceInMeters}m.`);
        }
    }
    
    class Dog extends Animal {
        bark() {
            console.log('Woof! Woof!');
        }
    }
    
    const dog = new Dog();
    dog.bark();
    dog.move(10);
    dog.bark();

    super

    如果父类的构造函数带参数,则子类调用父类构造函数时

    class Animal {
        name: string;
        constructor(theName: string) { this.name = theName; }
        move(distanceInMeters: number = 0) {
            console.log(`${this.name} moved ${distanceInMeters}m.`);
        }
    }
    
    class Snake extends Animal {
        constructor(name: string) { super(name); }
        move(distanceInMeters = 5) {
            console.log("Slithering...");
            super.move(distanceInMeters);
        }
    }
    
    class Horse extends Animal {
        constructor(name: string) { super(name); }
        move(distanceInMeters = 45) {
            console.log("Galloping...");
            super.move(distanceInMeters);
        }
    }
    
    let sam = new Snake("Sammy the Python");
    let tom: Animal = new Horse("Tommy the Palomino");
    
    sam.move();
    tom.move(34)

    在构造函数里访问 this的属性之前,我们 一定要调用 super()

     

    三、修饰符

    public

    在TypeScript里,成员都默认为 public

    private

    protected

    readonly

    class Octopus {
        readonly name: string;
        readonly numberOfLegs: number = 8;
        constructor (theName: string) {
            this.name = theName;
        }
    }
    let dad = new Octopus("Man with the 8 strong legs");
    dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.
  • 相关阅读:
    hdu 5146 Sequence
    hdu 1232 畅通工程
    hdu 1213 How Many Tables
    hdu 2822 Dogs
    hdu 1242 Rescue
    hdu 5101 Select
    hdu 1873 看病要排队
    hdu 5112 A Curious Matt
    hdu 5154 Harry and Magical Computer
    hdu 1548 A strange lift
  • 原文地址:https://www.cnblogs.com/buchizaodian/p/13803417.html
Copyright © 2011-2022 走看看