0
点赞
收藏
分享

微信扫一扫

Vue3+TypeScript从入门到精通系列之:抽象类

Vue3+TypeScript从入门到精通系列之:抽象类

一、TypeScript抽象类

(() => {

//抽象类:包含抽象方法,也可以包含实例方法
//抽象类不能被实例化,让子类进行实例化嗯及实现

//定义一个抽象类
abstract class Animal{
//抽象属性
abstract name: string
//抽象方法
abstract eat()

//实例方法
say(){
console.log(this.name,"都是动物")
}

}

class Dog extends Animal{
name: string = "小狗"
eat(){
  console.log(this.name,"喜欢吃骨头")
}
}

//实例化Dog对象
const dog:Dog = new Dog()
dog.eat()
dog.say()


})()

二、TypeScript抽象类代码转化为js代码

tsc ./抽象类.ts

抽象类.js代码如下所示:

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
(function () {
    //抽象类:包含抽象方法,也可以包含实例方法
    //抽象类不能被实例化,让子类进行实例化嗯及实现
    //定义一个抽象类
    var Animal = /** @class */ (function () {
        function Animal() {
        }
        //实例方法
        Animal.prototype.say = function () {
            console.log(this.name, "都是动物");
        };
        return Animal;
    }());
    var Dog = /** @class */ (function (_super) {
        __extends(Dog, _super);
        function Dog() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.name = "小狗";
            return _this;
        }
        Dog.prototype.eat = function () {
            console.log(this.name, "喜欢吃骨头");
        };
        return Dog;
    }(Animal));
    //实例化Dog对象
    var dog = new Dog();
    dog.eat();
    dog.say();
})();

三、js输出如下所示

node ./抽象类.js
小狗 喜欢吃骨头
小狗 都是动物
举报

相关推荐

0 条评论