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 是只读的.
  • 相关阅读:
    tomcat日志信息查看
    "".equals(xxx)和xxx.equals("")的区别
    javax.crypto.BadPaddingException: Given final block not properly padded解决方案
    去掉first li 的list图标
    浮动后的 <li> 如何在 <ul> 中居中显示?
    java冒泡排序
    JSP获取网络IP地址
    <%@ include %>导入的文件乱码
    out.print()与response.sendRedirect()
    王爽汇编语言第三版第5章实验4
  • 原文地址:https://www.cnblogs.com/buchizaodian/p/13803417.html
Copyright © 2011-2022 走看看