访问级别

1、public
在TypeScript里,成员都默认为 public。你也可以明确的将一个成员标记成public:

1
2
3
4
5
6
7
class Animal {
public name: string;
public constructor(theName: string) { this.name = theName; }
public move(distanceInMeters: number) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}

2、private
当成员被标记成private时,它就不能在声明它的类的外部访问。比如:

1
2
3
4
5
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
new Animal("Cat").name; // Error: 'name' is private;

当我们比较带有private或protected成员的类型的时候,情况就不同了。 如果其中一个类型里包含一个 private成员,那么只有当另外一个类型中也存在这样一个private成员, 并且它们都是来自同一处声明时,我们才认为这两个类型是兼容的。 对于 protected成员也使用这个规则:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
class Rhino extends Animal {
constructor() { super("Rhino"); }
}
class Employee {
private name: string;
constructor(theName: string) { this.name = theName; }
}
let animal = new Animal("Goat");
let rhino = new Rhino();
let employee = new Employee("Bob");
animal = rhino;
animal = employee; // Error: Animal and Employee are not compatible

3、protected
protected修饰符与private修饰符的行为很相似,但有一点不同,protected成员在派生类中仍然可以访问:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Animals{
private name:string;
protected pname:string
constructor(name:string,pname:string){
this.name=name;
this.pname=name;
}
}
class Dog extends Animals{
constructor(name:string,pname:string){
super(name,pname);
console.log(this.pname);//ok
console.log(this.name);//error
console.log(super.name);//error
console.log(super.pname);//error
}
}
let dog = new Dog("private","protected");
console.log(dog.name);//error
console.log(dog.pname);//error

4、static
static声明的属性为静态属性,有类+’.’调用

1
2
3
4
class Animal{
static Name="动物"
}
console.log(Animal.Name)

5、readonly
使用readonly关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化:

1
2
3
4
5
6
7
8
9
class Octopus {
readonly name: string;
readonly numberOfLegs: number = 8;
constructor (theName: string) {
this.name = theName;
}
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit";

总结

修饰符 访问级别
public 静态、实例、当前类、子类的属性与方法均可访问
static 仅可访问静态属性与方法
private 仅限当前类
protected 当前类和子类可访问

抽象类

抽象类不允许实例化,他可以给出某些属性、函数的实现,也可以不给交由子类实现

1
2
3
4
5
6
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log('roaming the earch...');
}
}

存取器

类似C#中的get;set;在JS阶段就有getter和setter了

简单使用

1
2
3
4
5
6
7
8
9
10
11
12
13
class Test{
private _value:number=10;
public get a():number{
return this._value;
}
public set a(value){
this._value=this._value+value
}
}
let t:Test = new Test();
console.log(t.a);
t.a=22;
console.log(t.a)

与C#对比

C#代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
internal class Program
{
static void Main(string[] args)
{
Test test = new Test();
Console.WriteLine(test.Value);
test.Value = 22;
Console.WriteLine(test.Value);
}
}
internal class Test
{
private int _value = 10;
public int Value
{
get { return this._value; }
set { this._value = value+this._value; }
}
}