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(12,42): The property 'name' does not exist on value of type 'Shape'
- class.ts(20,40): The property 'name' does not exist on value of type 'Shape'
- class.ts(22,41): The property 'width' does not exist on value of type 'Shape'
- class.ts(23,42): The property 'height' does not exist on value of type 'Shape'

接下来,我们添加 public 和 private 访问修饰符。Public 成员可以在任何地方访问, private 成员只允许在类中访问。
接下来我们修改以上代码,将 color 声明为 private,构造函数的参数 name 声明为 public:
- ...
- private color: string;
- ...
- constructor ( public name: string, width: number, height: number ) {
- ...

由于 color 成员变量设置了 private,所以会出现以下信息:
- class.ts(24,41): The property 'color' does not exist on value of type 'Shape'
转载本站内容时,请务必注明来自W3xue,违者必究。