最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • <笔记>typescript-类

    正文概述 掘金(一涯)   2021-01-11   391

    1. 类的继承和基本类型指定

    ts中super必须被调用,否则会提示

    Constructors for derived classes must contain a 'super' call

    class Animal {
        name: string;
        constructor(theName: string) { this.name = theName; }
        move(distanceInMeters: number = 0) {
            console.log(`${this.name} moved ${distanceInMeters}m.`);
        }
    }
    
    class Horse extends Animal {
        constructor(name: string) { super(name); } // 1.相当于super.call(this, props)
        move(distanceInMeters = 45) {
            console.log("Galloping...");        
            // 2. 相当于super.prototype.move.call(this, distanceInMeters)         super.move(distanceInMeters);
        }
    }
    let tom: Animal = new Horse("Tommy the Palomino");
    tom.move(34);
    

    2. 修饰符(公共/私有/受保护)

    1. 公共-public

    上面的类本质上为:

    class Animal {
        public name: string;
        public constructor(theName: string) { this.name = theName; }
        public move(distanceInMeters: number = 0) {
            console.log(`${this.name} moved ${distanceInMeters}m.`);
        }
    }
    

    2. 私有-private

    class Animal {  private name: string;  constructor(theName: string) { this.name = theName; }}new Animal("Cat").name; // 错误: 'name' 是私有的.
    
    class Animal {
        private name: string;
        constructor(theName: string) { this.name = theName; }
    }
    
    class Rhino extends Animal {
        constructor() { super("Rhino"); }
    }
    
    class Employee {
        private name: string;
        constructor(theName: string) { this.name = theName; }
    }
    
    let animal = new Animal("Goat");
    let rhino = new Rhino();
    let employee = new Employee("Bob");
    
    animal = rhino; // 正确。两者共享private成员
    animal = employee; // 错误: Animal 与 Employee 不兼容. 
    

    3. 受保护-protected

    class Person {
        protected name: string;
        constructor(name: string) { this.name = name; }
    }
    
    class Employee extends Person {
        private department: string;
    
        constructor(name: string, department: string) {
            super(name)
            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); // 错误;只能在声明类和子类中访问
    
    class Person {
        protected name: string;
        protected constructor(theName: string) { this.name = theName; }
    }
    
    // Employee 能够继承 Person
    class Employee extends Person {
        private department: string;
    
        constructor(name: string, department: string) {
            super(name);
            this.department = department;
        }
    
        public getElevatorPitch() {
            return `Hello, my name is ${this.name} and I work in ${this.department}.`;
        }
    }
    
    let howard = new Employee("Howard", "Sales");
    let john = new Person("John"); // 错误: 'Person' 的构造函数是被保护的.
    

    3. 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 是只读的.
    

    构造函数的参数属性

    class Octopus { // 和上面的代码等价
      readonly numberOfLegs: number = 8;
      constructor (readonly name: string) {
      }
    }
    

    4. 存取器(get/set)

    let passcode = "secret passcode";
    
    class Employee {
        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 Employee();
    employee.fullName = "Bob Smith";
    if (employee.fullName) {
        alert(employee.fullName);
    }
    

    5. 静态属性static

    直接通过类访问

    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) { }
    }
    
    let grid1 = new Grid(1.0);  // 1x scale
    let grid2 = new Grid(5.0);  // 5x scale
    
    console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));
    console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));
    

    6. 抽象类-abstract

    abstract作用:

    1. 定义抽象类(抽象类不能被实例化)
    2. 定义抽象类内部的抽象方法(不包含具体实现并且必须在派生类中实现

    abstract应用:

    abstract class Animal { // 抽象类 
     abstract makeSound(): void; // 抽象方法不包含具体实现 
     move(): void { // 非抽象方法可以包含具体实现    
        console.log('roaming the earch...');  
    }}
    

    示例:

    abstract class Department {  
        constructor(public name: string) {  
        }  
        printName(): void {   
            console.log('Department name: ' + this.name);  
        }  
        abstract printMeeting(): void;
    }
    class AccountingDepartment extends Department {  
            constructor() {    
                super("Accounting and Auditing");  
            }  
            printMeeting(): void {    
                console.log('The Accounting Department meets each Monday at 10am.');  
            }  
            generateReports(): void {    
                console.log('Generating accounting reports...');  
            }
    }
    let department: Department; // 定义变量的类型
    department = new Department(); //  ❌不能被实例话
    department = new AccountingDepartment();
    department.printMeeting();
    department.printName();
    department.generateReports(); // ❌方法声明在抽象类中不存在
    

    6. 高级技巧-构造函数

    在ts中声明类的时候,同时声明了实例类型构造函数

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

    其编译成javascript的结果如下:

    var Greeter = (function() {  
        function Greeter(message) {    
            this.greeting = message;  
        }  
        Greeter.prototype.greet = function() {    
            return "Hello, " + this.greeting; 
        }  
        return Greeter
    }());
    var greeter;
    greeter = new Greeter("world");
    console.log(greeter.greet());
    

    起源地下载网 » <笔记>typescript-类

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元