1. ts 中类的定义
class Person{
name!:string;
age:number;
constructor(name:string, age:number) {
this.name = name;
this.age = age;
}
running(){
console.log(this.name + " running")
}
eating(){
console.log(this.name + " eating")
}
}
let p = new Person("ES6+",7)
p.running()
p.eating()
2. ts 类的类型
let p2: A = {
name: "p two",
age: 18,
running(){},
eating(){}
}
3. ts 类的继承 extends
// error Classes can only extend a single class.
// class Student extends Person, A{}
// -------------------------------
class Student extends Person{
learn: string;
constructor(name:string, age:number, learn: string) {
super(name, age);
this.learn = learn
}
running(){
//this ==> s
//super===> Person
super.running()
console.log(this.name + " Student running")
}
}
4. ts 类的成员修饰符
在typeScript中 类的属性和方法支持三种修饰符
1 public 修饰的属性或方法是公有的,可以在任何地方被访问到,默认的是 public
2 private 修饰的属性或方法是私有的,不能在声明它的类的外部访问(不参与继承)
3 protected 修饰的属性或方法是受保护的,在子类中也是允许被访问的
4 readonly 修饰的是这个属性我们不希望外界可以任意的修改,只希望确定值之后直接使用(只能读)
1. public
class Person{
public name!:string;
public age:number;
// ...
}
class Student extends Person{
public learn: string;
constructor(name:string, age:number, learn: string) {
super(name, age);
this.learn = learn
}
running(){
//this ==> s
//super===> Person
super.running()
console.log(this.name + " Student running") // studentStudent running
}
}
let s: Student = new Student("student", 18, "TypeScript");
s.running();
console.log(s) // Student { name: 'student', age: 20, learn: 'TypeScript' }
2. private
class Person{
private name:string;
constructor(name:string) {
this.name = name;
}
}
let p = new Person("aa"); // {name: 'a'}
3. protected
class Person{
protected name:string;
constructor(name:string) {
this.name = name;
}
}
let p = new Person("aa");
// error Property 'name' is protected and only accessible within class 'Person' and its subclasses.
console.log("=======>",p.name)
4. readonly
class Person{
readonly name:string;
constructor(name:string) {
this.name = name;
}
}
let p = new Person("aa");
// p.name = '123123'; // error Cannot assign to 'name' because it is a read-only property.
console.log(p.name); // 'aa'