基本类
class A {
mingzi: string
xingbie: string
constructor(x: string, y: string) {
this.mingzi = x;
this.xingbie = y
}
xx() {
console.log(`我很牛逼,我叫${this.mingzi},我是${this.xingbie}的`);
}
}
let xxxx = new A("马牛逼", "男")
xxxx.xx()
函数的继承
export default {}
class A {
mingzi: string
xingbie: string
constructor(x: string, y: string) {
this.mingzi = x;
this.xingbie = y
}
xx() {
console.log(`我很牛逼,我叫${this.mingzi},我是${this.xingbie}的`);
}
}
let xxxx = new A("马牛逼", "男")
xxxx.xx()
class Erzi extends A {
nianling: number
constructor(x: string, y: string, z: number) {
super(x, y)
this.nianling = z
}
xxx(){
super.xx()
console.log(`我很牛逼,我叫${this.mingzi},我是${this.xingbie}的,我${this.nianling}岁了`);
}
}
static和instanceof
export default {}
// static和instanceof
// static关键字用于定义类的数据成员(属性和方法)为静态的,静态成员可以直接通过类名调用
class At{
static a1: string
static sayHello():void{
console.log(`我希望的工资是${At.a1}`);
}
}
At.a1 = "18k"
At.sayHello()
// instanceof运算符
// instanceof运算符用于判断对象是否是指定的类型,如果是返回true,否则返回false,
class Person{}
let p1 = new Person()
let p2= p1 instanceof Person
console.log(p2); //true
console.log("------------");
// 继承了父类
class Person1 extends Person{}
let t1 = new Person()
let t2 = t1 instanceof Person
console.log(t2); //true
修饰符
export default{}
// public(默认):公有,可以在任何地方被访问
// protected:受保'。可以被其血守以及其子类访问
// private:私有,只能被其定义所在的类访问。
// readonly:可以使用readon1y关键宁将属性设置为只读的。只读属性必须在声明时或枫迢函数里被初始化
class Person{
public name:string
protected age:number
private aa:string
// 字段
constructor(n:string,a:number,aa1:string){
this.name = n
this.age = a
this.aa = aa1
// 构造函数
}
// 函数(方法)
sayHello():void{
console.log(`他叫${this.name},他今年${this.age}岁`);
}
}
// readonly:可以使用readon1y关键宁将属性设置为只读的。只读属性必须在声明时或枫迢函数里被初始化
class Aq{
readonly str1:string = "HTML"
readonly str2:string
readonly str3:string
readonly str4:string
readonly str5:string
constructor(str2:string, str3:string,str4:string,str5:string){
this.str2 = str2
this.str3 = str3
this.str4 = str4
this.str5 = str5
}
}
let pc = new Aq("q","W","e","r")
console.log(pc);
实现函数的取存
export default {}
class GetNameclass {
private _fuName: string = "倪妮"
get fuName(): string {
console.log("我是get方法");
return this._fuName
}
set fuName(newName: string) {
console.log("我是set方法");
this._fuName = newName;
}
}
let starname = new GetNameclass();
starname.fuName = "袁冰妍"
console.log(starname);
console.log(starname.fuName);
类抽象
export default {}
abstract class Person {
abstract name: string;
abstract show(): string;
showName() {
console.log(this.show());
}
}
class Student extends Person {
name: string = "孟子义";
show(): string {
return "陈情令"
}
}
//Let p = new Person();
let s = new Student();
let res = s.show();
console.log(res);