private
使用private
标识的成员变量,不允许在本类之外的地方使用.
class Auto{
private engine: string;
constructor(engine:string){
this.engine = engine;
}
}
var engine = new Auto('').engine; //错误
之前我们说过当两个类有相同的属性和方法时可以互相赋值.例如:
class One{
name: string;
say(){ /*...*/ }
}
class Two{
name: string;
say(){ /*...*/ }
}
var one = new One();
var two = new Two();
one = two;
但如果加上private
的话就会得到一个错误 :
class One{
private name: string;
say(){ /*...*/ }
}
class Two{
private name: string;
say(){ /*...*/ }
}
var one = new One();
var two = new Two();
one = two; //错误, 不同源private之间不可以互相赋值
class Three extends One{
}
var three = new Three();
one = three; //正确
protected
protected可以在本类及其子类中访问
class ListString {
private contents: string[];
constructor() {
this.contents = [];
}
protected setElement(index: number, item: string) {
this.contents[index] = item;
}
}
class StackString extends ListString {
currentIndex: number;
constructor() {
super();
this.currentIndex = 0;
}
public push(item: string) {
this.setElement(this.currentIndex, item);
this.currentIndex++;
}
}
var stack = new StackString();
//stack.setElement(0, 1); // 错误 'setElement' 是protected,不可以在外部访问
static
使用静态变量或方法可以使用类别.方法名
或类别.变量名
的方式使用
class MyClass{
static name:string = 'Tom';
static foo(){
console.log("foo");
}
}
MyClass.foo();
MyClass.name