- 类的基本使用
export default {};
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
sayHello(): void {
console.log(
`我的女神是${this.name},她今年${this.age}岁了,但是在我的心里,她永远18岁`
);
}
}
let p = new Person("邱淑贞", 54);
p.sayHello();
- 类的继承
export default {};
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
say(): void {
console.log(`我是${this.name}, 今年${this.age}岁了`);
}
}
class Student extends Person {
score: string;
constructor(name: string, age: number, score: string) {
super(name, age);
this.score = score;
}
say(): void {
super.say();
console.log(
`我是重写之后的say方法, 我是学生${this.name}, 今年${this.age}岁了,我的成绩为${this.score}`
);
}
}
let s = new Student("蒋依依", 18, "A");
s.say();
- static 与 Instanceof
export default {};
class StaticTest {
static salary: string;
static say(): void {
console.log("我们想要的工资是: " + this.salary);
}
}
StaticTest.salary = "18k";
StaticTest.say();
class Person {}
let p = new Person();
let isPerson = p instanceof Person;
console.log("p对象是Person类实例化来的嘛?" + isPerson);
class Student extends Person {}
let s = new Student();
let isPerson2 = s instanceof Person;
console.log("p对象是Person类实例化来的嘛?" + isPerson2);
- 类中的修饰符
export default {};
class Person {
public name: string;
protected age: number;
private sex: string;
constructor(name: string, age: number, sex: string) {
this.name = name;
this.age = age;
this.sex = sex;
}
say(): void {
console.log(
`我的名字是${this.name}, 性别为${this.sex}, 今年${this.age}岁了`
);
}
}
let p = new Person("邱淑贞", 18, "女");
p.say();
class Student extends Person {
score: string;
constructor(name: string, age: number, sex: string, score: string) {
super(name, age, sex);
this.score = score;
}
show(): void {
console.log(this.name);
console.log(this.age);
console.log(this.score);
}
}
class PrintConsole {
readonly str1: string = "HTML, CSS, JS, VUE, REACT, NODE";
readonly str2: string;
readonly str3: string;
readonly str4: string;
constructor(str2: string, str3: string, str4: string) {
this.str2 = str2;
this.str3 = str3;
this.str4 = str4;
}
}
let pc = new PrintConsole(
"我的头发去哪了, 颈椎康复指南",
"35岁失业了该怎么办, 外卖月入一万也挺好",
"活着"
);
- getter 与 setter
export default {};
class GetNameClass {
private _fullName: string = "倪妮";
get fullName(): string {
console.log("我是get方法");
return this._fullName;
}
set fullName(newName: string) {
console.log("我是set方法");
this._fullName = newName;
}
}
let startname = new GetNameClass();
startname.fullName = "袁冰妍";
console.log(startname.fullName);