TypeScript-类

2019-07-15  本文已影响0人  叶小七的真命天子
// 类继承
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")
sam.move()
// Slithering...
// Sammy the Python moved 5m.

let tom :Animal = new Horse("Tommy the Palomino"); 
// 即使 tom被声明为 Animal类型,但因为它的值是 Horse,调用 tom.move(34)时,它会调用 Horse里重写的方法
tom.move(333)
// Galloping...
// Tommy the Palomino moved 333m.


// 类成员属性, 默认public
// 当成员被标记成 private时,它就不能在声明它的类的外部访问
class Person {
    private name: string;
    constructor(theName: string) { this.name = theName; }
}

class Student extends Person {
    constructor() { super("Rhino"); }
}
const bob = new Student()
// bob.name  error

// protected修饰符与 private修饰符的行为很相似,但有一点不同, protected成员在派生类中仍然可以访问
class Person2 {
    protected name: string;
    constructor(name: string) { this.name = name; }
}

class Employee extends Person2 {
    private department: string;

    constructor(name: string, department: string) {
        super(name)
     // this.name = '11111'
        this.department = department;
    }

    public getElevatorPitch() {
        return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
}

let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
// console.log(howard.name); // 错误

// 参数属性
// 参数属性通过给构造函数参数前面添加一个访问限定符来声明。
// 使用 private限定一个参数属性会声明并初始化一个私有成员;对于 public和 protected来说也是一样。
class Octopus {
    readonly numberOfLegs: number = 8;
    constructor(private name: string) {
    }
}

const nsjd = new Octopus('bob')
//const bobName = nsjd.name //error

//存储器
let passcode = "secret passcode2";

class Employee4 {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee4();
employee.fullName = "Bob Smith"; // Error: Unauthorized update of employee!
if (employee.fullName) {
    alert(employee.fullName);
}

// 类的静态属性
class Book{
    constructor(public bookName:string){}
    static getName(){
        return `i am a static method`
    }
}
const abc = new Book('Harry Port')
console.log(abc.bookName)  //成员变量
console.log(Book.getName()) //静态方法


// 抽象类
// 抽象类做为其它派生类的基类使用。 它们一般不会直接被实例化。
// 抽象类中的抽象方法不包含具体实现并且必须在派生类中实现

abstract class Computer{
    constructor(public type:string){}
    printType():void{
        console.log(this.type)
    }
    abstract printPrice(price:number):void  // 抽象方法
}
class Mac extends Computer{
    constructor(type:string){
        super(type)
        console.log('start constructor')
    }
    printPrice(price:number):void{  //实现抽象方法
        console.log(`the ${this.type} computer's price is ${price}`)
    }

    getSoft():void{
        console.log('hello wold')
    }
}

const macpro =  new Mac('MacBook Pro')
macpro.printType()
macpro.printPrice(13000)
macpro.getSoft()

class Greeter {
    static standardGreeting = "Hello, there";
    greeting: string;
    greet() {
        if (this.greeting) {
            return "Hello, " + this.greeting;
        }
        else {
            return Greeter.standardGreeting;
        }
    }
}

let greeter1: Greeter;
greeter1 = new Greeter();
console.log(greeter1.greet());

let greeterMaker: typeof Greeter = Greeter;
greeterMaker.standardGreeting = "Hey there!";

let greeter2: Greeter = new greeterMaker();
console.log(greeter2.greet());

















上一篇下一篇

猜你喜欢

热点阅读