教程 > typescript 教程 > 阅读:52

typescript 类——迹忆客-ag捕鱼王app官网

typescript 是面向对象的 javascript。

类描述了所创建的对象共同的属性和方法。

typescript 支持面向对象的所有特性,比如 类、接口等。

typescript 类定义方式如下:

class class_name { 
    // 类作用域
}

定义类的关键字为 class,后面紧跟类名,类可以包含以下几个模块(类的数据成员):

  • 字段 − 字段是类里面声明的变量。字段表示对象的有关数据。
  • 构造函数 − 类实例化时调用,可以为类的对象分配内存。
  • 方法 − 方法为对象要执行的操作。

实例

创建一个 person 类:

typescript

class person {
}

编译以上代码,得到以下 javascript 代码:

javascript

var person = /** @class */ (function () {
    function person() {
    }
    return person;
}());

创建类的数据成员

以下实例我们声明了类 car,包含字段为 engine,构造函数在类实例化后初始化字段 engine。

this 关键字表示当前类实例化的对象。注意构造函数的参数名与字段名相同,this.engine 表示类的字段。

此外我们也在类中定义了一个方法 disp()。

typescript

class car { 
    // 字段 
    engine:string; 
 
    // 构造函数 
    constructor(engine:string) { 
        this.engine = engine 
    }  
 
    // 方法 
    disp():void { 
        console.log("发动机为 :   " this.engine) 
    } 
}

编译以上代码,得到以下 javascript 代码:

javascript

var car = /** @class */ (function () {
    // 构造函数 
    function car(engine) {
        this.engine = engine;
    }
    // 方法 
    car.prototype.disp = function () {
        console.log("发动机为 :   "   this.engine);
    };
    return car;
}());

创建实例化对象

我们使用 new 关键字来实例化类的对象,语法格式如下:

var object_name = new class_name([ arguments ])

类实例化时会调用构造函数,例如:

var obj = new car("engine 1")

类中的字段属性和方法可以使用 . 号来访问:

// 访问属性
obj.field_name 
// 访问方法
obj.function_name()

完整实例

以下实例创建来一个 car 类,然后通过关键字 new 来创建一个对象并访问属性和方法:

typescript

class car { 
   // 字段
   engine:string; 
   
   // 构造函数
   constructor(engine:string) { 
      this.engine = engine 
   }  
   
   // 方法
   disp():void { 
      console.log("函数中显示发动机型号  :   " this.engine) 
   } 
} 
 
// 创建一个对象
var obj = new car("xxsy1")
 
// 访问字段
console.log("读取发动机型号 :  " obj.engine)  
 
// 访问方法
obj.disp()

编译以上代码,得到以下 javascript 代码:

javascript

var car = /** @class */ (function () {
    // 构造函数
    function car(engine) {
        this.engine = engine;
    }
    // 方法
    car.prototype.disp = function () {
        console.log("函数中显示发动机型号  :   "   this.engine);
    };
    return car;
}());
// 创建一个对象
var obj = new car("xxsy1");
// 访问字段
console.log("读取发动机型号 :  "   obj.engine);
// 访问方法
obj.disp();

输出结果为:

读取发动机型号 :  xxsy1
函数中显示发动机型号  :   xxsy1

类的继承

typescript 支持继承类,即我们可以在创建类的时候继承一个已存在的类,这个已存在的类称为父类,继承它的类称为子类。

类继承使用关键字 extends,子类除了不能继承父类的私有成员(方法和属性)和构造函数,其他的都可以继承。

typescript 一次只能继承一个类,不支持继承多个类,但 typescript 支持多重继承(a 继承 b,b 继承 c)。

语法格式如下:

class child_class_name extends parent_class_name

实例

类的继承:实例中创建了 shape 类,circle 类继承了 shape 类,circle 类可以直接使用 area 属性:

typescript

class shape { 
   area:number 
   
   constructor(a:number) { 
      this.area = a 
   } 
} 
 
class circle extends shape { 
   disp():void { 
      console.log("圆的面积:  " this.area) 
   } 
}
  
var obj = new circle(223); 
obj.disp()

编译以上代码,得到以下 javascript 代码:

javascript

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 (b.hasownproperty(p)) d[p] = b[p]; };
        return extendstatics(d, b);
    };
    return function (d, b) {
        extendstatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var shape = /** @class */ (function () {
    function shape(a) {
        this.area = a;
    }
    return shape;
}());
var circle = /** @class */ (function (_super) {
    __extends(circle, _super);
    function circle() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    circle.prototype.disp = function () {
        console.log("圆的面积:  "   this.area);
    };
    return circle;
}(shape));
var obj = new circle(223);
obj.disp();

输出结果为:

圆的面积:  223

需要注意的是子类只能继承一个父类,typescript 不支持继承多个类,但支持多重继承,如下实例:

typescript

class root { 
   str:string; 
} 
 
class child extends root {} 
class leaf extends child {} // 多重继承,继承了 child 和 root 类
 
var obj = new leaf(); 
obj.str ="hello" 
console.log(obj.str)

编译以上代码,得到以下 javascript 代码:

javascript

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 (b.hasownproperty(p)) d[p] = b[p]; };
        return extendstatics(d, b);
    };
    return function (d, b) {
        extendstatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var root = /** @class */ (function () {
    function root() {
    }
    return root;
}());
var child = /** @class */ (function (_super) {
    __extends(child, _super);
    function child() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return child;
}(root));
var leaf = /** @class */ (function (_super) {
    __extends(leaf, _super);
    function leaf() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return leaf;
}(child)); // 多重继承,继承了 child 和 root 类
var obj = new leaf();
obj.str = "hello";
console.log(obj.str);

输出结果为:

hello

继承类的方法重写

类继承后,子类可以对父类的方法重新定义,这个过程称之为方法的重写。

其中 super 关键字是对父类的直接引用,该关键字可以引用父类的属性和方法。

typescript

class printerclass { 
   doprint():void {
      console.log("父类的 doprint() 方法。") 
   } 
} 
 
class stringprinter extends printerclass { 
   doprint():void { 
      super.doprint() // 调用父类的函数
      console.log("子类的 doprint()方法。")
   } 
}

编译以上代码,得到以下 javascript 代码:

javascript

var obj = new stringprinter() 
obj.doprint()
 
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 (b.hasownproperty(p)) d[p] = b[p]; };
        return extendstatics(d, b);
    };
    return function (d, b) {
        extendstatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var printerclass = /** @class */ (function () {
    function printerclass() {
    }
    printerclass.prototype.doprint = function () {
        console.log("父类的 doprint() 方法。");
    };
    return printerclass;
}());
var stringprinter = /** @class */ (function (_super) {
    __extends(stringprinter, _super);
    function stringprinter() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    stringprinter.prototype.doprint = function () {
        _super.prototype.doprint.call(this); // 调用父类的函数
        console.log("子类的 doprint()方法。");
    };
    return stringprinter;
}(printerclass));
var obj = new stringprinter();
obj.doprint();

输出结果为:

父类的 doprint() 方法。
子类的 doprint()方法。

static 关键字

static 关键字用于定义类的数据成员(属性和方法)为静态的,静态成员可以直接通过类名调用。

typescript

class staticmem {  
   static num:number; 
   
   static disp():void { 
      console.log("num 值为 "  staticmem.num) 
   } 
} 
 
staticmem.num = 12     // 初始化静态变量
staticmem.disp()       // 调用静态方法

编译以上代码,得到以下 javascript 代码:

javascript

var staticmem = /** @class */ (function () {
    function staticmem() {
    }
    staticmem.disp = function () {
        console.log("num 值为 "   staticmem.num);
    };
    return staticmem;
}());
staticmem.num = 12; // 初始化静态变量
staticmem.disp(); // 调用静态方法

输出结果为:

num 值为 12

instanceof 运算符

instanceof 运算符用于判断对象是否是指定的类型,如果是返回 true,否则返回 false。

typescript

class person{ } 
var obj = new person() 
var isperson = obj instanceof person; 
console.log("obj 对象是 person 类实例化来的吗? "   isperson);

编译以上代码,得到以下 javascript 代码:

javascript

var person = /** @class */ (function () {
    function person() {
    }
    return person;
}());
var obj = new person();
var isperson = obj instanceof person;
console.log(" obj 对象是 person 类实例化来的吗? "   isperson);

输出结果为:

obj 对象是 person 类实例化来的吗? true

访问控制修饰符

typescript 中,可以使用访问控制符来保护对类、变量、方法和构造方法的访问。typescript 支持 3 种不同的访问权限。

  • public(默认) : 公有,可以在任何地方被访问。
  • protected : 受保护,可以被其自身以及其子类和父类访问。
  • private : 私有,只能被其定义所在的类访问。

以下实例定义了两个变量 str1 和 str2,str1 为 public,str2 为 private,实例化后可以访问 str1,如果要访问 str2 则会编译错误。

typescript

class encapsulate { 
   str1:string = "hello" 
   private str2:string = "world" 
}
 
var obj = new encapsulate() 
console.log(obj.str1)     // 可访问 
console.log(obj.str2)   // 编译错误, str2 是私有的

类和接口

类可以实现接口,使用关键字 implements,并将 interest 字段作为类的属性使用。

以下实例红 agriloan 类实现了 iloan 接口:

typescript

interface iloan { 
   interest:number 
} 
 
class agriloan implements iloan { 
   interest:number 
   rebate:number 
   
   constructor(interest:number,rebate:number) { 
      this.interest = interest 
      this.rebate = rebate 
   } 
} 
 
var obj = new agriloan(10,1) 
console.log("利润为 : " obj.interest ",抽成为 : " obj.rebate )

编译以上代码,得到以下 javascript 代码:

javascript

var agriloan = /** @class */ (function () {
    function agriloan(interest, rebate) {
        this.interest = interest;
        this.rebate = rebate;
    }
    return agriloan;
}());
var obj = new agriloan(10, 1);
console.log("利润为 : "   obj.interest   ",抽成为 : "   obj.rebate);

输出结果为:

利润为 : 10,抽成为 : 1

查看笔记

扫码一下
查看教程更方便
网站地图