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 是只读的.
  • 相关阅读:
    关于在函数中返回动态的内存
    C与C++中的const
    strcat函数的坑点
    面试题30.最小的k个数
    面试题29.数组中出现次数超过一半的数字
    面试题28.字符串的排列
    面试题27.二叉搜索树与双向链表
    C++中构造函数初始化成员列表总结
    Oracle merge into
    检索 COM 类工厂中 CLSID 解决办法
  • 原文地址:https://www.cnblogs.com/buchizaodian/p/13803417.html
Copyright © 2011-2022 走看看