访问权限控制
public & private & protected
- public,修饰的属性或方法是共有的
- private,私有属性
- 只能在类里面进行访问,不能在类的外部调用;
- 实例化的对象无法访问
- protected,受保护的
- 子类可以继承和访问
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) }
run () {// super 调用父类的方法return 'mao,' + super.run()}
} const mao = new Child(‘maomao’)
<a name="hglDx"></a>## static静态属性```typescriptclass Animal {pbulic name: string; // 公共属性,默认值private name: string; // 属性,子类不能继承,外部不可访问protected name: string; // 子类可以继承readonly name: string; // 只读属性,重新赋值会报错// 静态属性static category: string[] = ['bird', 'duck']// 静态方法static isInstance (a) {return a instanceof Animal}constructor(name: string) {this.name = name}run() { // 方法return `${this.name} is animal`}}class Person{// 成员 属性name:string// 构造函数constructor(nameNew:string){this.name = nameNew;}// 方法info(){return this.name;}}
编译成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();
