课程表

TypeScript课程

工具箱
速查手册

TypeScript 类

当前位置:免费教程 » JS/JS库/框架 » TypeScript

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

接下来我们创建一个类文件 class.ts,代码如下:

  1. class Shape {
  2. area: number;
  3. color: string;
  4. constructor ( name: string, width: number, height: number ) {
  5. this.area = width * height;
  6. this.color = "pink";
  7. };
  8. shoutout() {
  9. return "I'm " + this.color + " " + this.name + " with an area of " + this.area + " cm squared.";
  10. }
  11. }
  12. var square = new Shape("square", 30, 30);
  13. console.log( square.shoutout() );
  14. console.log( 'Area of Shape: ' + square.area );
  15. console.log( 'Name of Shape: ' + square.name );
  16. console.log( 'Color of Shape: ' + square.color );
  17. console.log( 'Width of Shape: ' + square.width );
  18. console.log( 'Height of Shape: ' + square.height );

以上 Shape 类中有两个属性 area 和 color,一个构造器 (constructor()), 一个方法是 shoutout() 。

构造器中参数(name, width 和 height) 的作用域是局部变量,所以编译以上文件,在浏览器输出错误结果如下所示:

  1. class.ts(12,42): The property 'name' does not exist on value of type 'Shape'
  2. class.ts(20,40): The property 'name' does not exist on value of type 'Shape'
  3. class.ts(22,41): The property 'width' does not exist on value of type 'Shape'
  4. class.ts(23,42): The property 'height' does not exist on value of type 'Shape'
显示结果

接下来,我们添加 public 和 private 访问修饰符。Public 成员可以在任何地方访问, private 成员只允许在类中访问。

接下来我们修改以上代码,将 color 声明为 private,构造函数的参数 name 声明为 public:

  1. ...
  2. private color: string;
  3. ...
  4. constructor ( public name: string, width: number, height: number ) {
  5. ...

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

  1. class.ts(24,41): The property 'color' does not exist on value of type 'Shape'
转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号