访问权限控制

public & private & protected

  1. public,修饰的属性或方法是共有的
  2. private,私有属性
    1. 只能在类里面进行访问,不能在类的外部调用;
    2. 实例化的对象无法访问
  3. protected,受保护的
    1. 子类可以继承和访问
  4. readonly 只读 ```javascript class Parent { readonly name: string;

    constructor (name: string) { this.name = name }

    private run () { // 只能在 Parent类里面访问,外部和子类都无法访问 return ${this.name} is runing } }

// extends 继承 class Child extends Parent { constructor(name) { super(name) console.log(‘cat name’, name) }

  1. run () {
  2. // super 调用父类的方法
  3. return 'mao,' + super.run()
  4. }

} const mao = new Child(‘maomao’)

  1. <a name="hglDx"></a>
  2. ## static静态属性
  3. ```typescript
  4. class Animal {
  5. pbulic name: string; // 公共属性,默认值
  6. private name: string; // 属性,子类不能继承,外部不可访问
  7. protected name: string; // 子类可以继承
  8. readonly name: string; // 只读属性,重新赋值会报错
  9. // 静态属性
  10. static category: string[] = ['bird', 'duck']
  11. // 静态方法
  12. static isInstance (a) {
  13. return a instanceof Animal
  14. }
  15. constructor(name: string) {
  16. this.name = name
  17. }
  18. run() { // 方法
  19. return `${this.name} is animal`
  20. }
  21. }
  22. class Person{
  23. // 成员 属性
  24. name:string
  25. // 构造函数
  26. constructor(nameNew:string){
  27. this.name = nameNew;
  28. }
  29. // 方法
  30. info(){
  31. return this.name;
  32. }
  33. }

编译成js

var Person = /** @class */ (function () {
  // 构造函数
  function Person(nameNew) {
    this.name = nameNew;
  }

  // 方法
  Person.prototype.info = function () {
    return this.name;
  };

  return Person;
}());

// 实例化一个Person类的对象
var person = new Person("lucy");

extends子类继承父类

class Animal{
    // 可见度
    public name:string;
    private age:number;
    protected sex:string;
}

class Cat extends Animal{

}

编译成 js

var __extends = (this && this.__extends) || (function () {
  var 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 function (d, b) {
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
})();


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

var Cat = /** @class */ (function (_super) {
  __extends(Cat, _super);
  function Cat() {
    return _super !== null && _super.apply(this, arguments) || this;
  }
  return Cat;
}(Animal));

var dong = new Cat();