TypeScript 类

TypeScript 支持集成了可选的类型批注支持的 ECMAScript 6 的类

下面我们来创建一个类文件 class.ts,内容如下

class Shape
{

    area: number;
    color: string;

    constructor ( name: string, width: number, height: number ) {
        this.area = width * height;
        this.color = "pink";
    };

    shoutout() {
        return "I'm " + this.color + " " + this.name +  " with an area of " + this.area + " cm squared.";
    }
}

var square = new Shape("square", 30, 30);

console.log( square.shoutout() );
console.log( 'Area of Shape: ' + square.area );
console.log( 'Name of Shape: ' + square.name );
console.log( 'Color of Shape: ' + square.color );
console.log( 'Width of Shape: ' + square.width );
console.log( 'Height of Shape: ' + square.height );

上面的 Shape 类包含两个属性 area 和 color,一个构造器 (constructor()), 一个方法 shoutout()

构造器中参数(name, width 和 height) 的作用域是局部变量

当我们编译 class.ts 文件,会发生错误,错误信息如下

$ tsc class.ts                                     
class.ts(13,49): error TS2339: Property 'name' does not exist on type 'Shape'.
class.ts(21,41): error TS2339: Property 'name' does not exist on type 'Shape'.
class.ts(23,42): error TS2339: Property 'width' does not exist on type 'Shape'.
class.ts(24,43): error TS2339: Property 'height' does not exist on type 'Shape'.

访问修饰符

然后,我们添加 public 和 private 访问修饰符

  1. Public 成员可以在任何地方访问
  2. private 成员只允许在类中访问

修改上面的代码,将 color 声明为 private,构造函数的参数 name 声明为 public

...
private color: string;
...
constructor ( public name: string, width: number, height: number ) {
...

由于 color 成员变量设置了 private,所以会出现以下错误信息

$ tsc class.ts
class.ts(22,42): error TS2341: Property 'color' is private and only accessible within class 'Shape'.
class.ts(23,42): error TS2339: Property 'width' does not exist on type 'Shape'.
class.ts(24,43): error TS2339: Property 'height' does not exist on type 'Shape'.

所以,如果要正确的声明这个类,需要修改成以下内容

class Shape
{

    area: number;
    color: string;
    width:number;
    height:number;

    constructor ( public name: string, width: number, height: number ) {
        this.area = width * height;
        this.color = "pink";
    };

    shoutout() {
        return "I'm " + this.color + " " + this.name +  " with an area of " + this.area + " cm squared.";
    }
}

var square = new Shape("square", 30, 30);

console.log( square.shoutout() );
console.log( 'Area of Shape: ' + square.area );
console.log( 'Name of Shape: ' + square.name );
console.log( 'Color of Shape: ' + square.color );
console.log( 'Width of Shape: ' + square.width );
console.log( 'Height of Shape: ' + square.height );

这时候编译就不会出错了

运行以上脚本,输出结果如下

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.