Typescript learning - class

extends the derived class

Derived class contains a constructor, it must be called super(), it will execute the constructor of the base class. Also, before accessing this property in the constructor, we must call super(). This is an important rule TypeScript enforcement.

public, private, protected difference

  • The default value is public, the public
  • private is private, inheritance or instantiation can access
  • protected is the type of protection, inheritance can be accessed, not instantiation

Static property static keyword

class Grid {
    static origin = {x: 0, y: 0};
    calculateDistanceFromOrigin(point: {x: number; y: number;}) {
        let xDist = (point.x - Grid.origin.x);
        let yDist = (point.y - Grid.origin.y);
        return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
    }
    constructor (public scale: number) { }
}

Into js

var Grid = function(){
    this.origin = {x: 0, y: 0};
}
Grid.prototype.calculateDistanceFromOrigin = () => {
    let xDist = (point.x - Grid.origin.x);
    let yDist = (point.y - Grid.origin.y);
    return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale; 
}
Grid.origin = {x: 0, y: 0};

Abstract class abstract

abstract class ParentClass {
    // 抽象类中定义的抽象方法,必须在子类中实现
    abstract ParentFun(): void;
}

Examples of the type of

class Greeter { 
    greeting: string;
    constructor(greeting: string) { 
        this.greeting = greeting
    }
    onGreet() { 
        console.log(this.greeting);
    }
}
// 实例的类型是 Greeter 类
let greet: Greeter;
greet = new Greeter('hello');
greet.onGreet();

The class interface with one

class Point {
    x: number;
    y: number;
}

interface Point3d extends Point {
    z: number;
}

let point3d: Point3d = { x: 1, y: 2, z: 3 };

You can create a class type, you can use class interface

What represents a class or interface type? ? ?
Ts class conversion code will be converted into function ...
the interface is only at compile time to do the type of agreement, it will not turn into any code

interface Point {
    x: number;
    y: number;
}

interface Point3d extends Point {
    z: number;
}

let point3d: Point3d = { x: 1, y: 2, z: 3 };

Into js

var point3d = { x: 1, y: 2, z: 3 };

Guess you like

Origin www.cnblogs.com/ubuntugx/p/11492169.html