前言
TypeScript 类方法修饰符用于控制类成员方法的访问权限和行为
类的方法修饰符和属性的修饰符一样,只不过方法的修饰符是没有
readonly
的
博主假设有这么一个需求: 有一个基类, 所有的子类都需要继承于这个基类, 但是我们不希望别人能够通过基类来创建对象:
错误示例:
class Person { name: string; age: number; gender: string; protected constructor(name: string, age: number, gender: string) { this.name = name; this.age = age; this.gender = gender; } say(): void { console.log(`name=${this.name},age=${this.age},gender=${this.gender}`); } } class Student extends Person { constructor(name: string, age: number, gender: string) { super(name, age, gender); } } let p = new Person('BNTang', 18, 'male'); let stu = new Student('zs', 18, 'female');
正确示例:
class Person { name: string; age: number; gender: string; protected constructor(name: string, age: number, gender: string) { this.name = name; this.age = age; this.gender = gender; } say(): void { console.log(`name=${this.name},age=${this.age},gender=${this.gender}`); } } class Student extends Person { constructor(name: string, age: number, gender: string) { super(name, age, gender); } } let stu = new Student('zs', 18, 'female'); console.log(stu);
可选属性
和接口中的可选属性一样, 可传可不传的属性
注意点
在
TS
中如果定义了实例属性, 那么就必须在构造函数中使用, 否则就会报错
错误示例:
class Person { name: string; age: number; }
正确示例:
class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } } let p = new Person('BNTang', 18); console.log(p);
利用 可选参数
解决不想使用的属性:
class Person { name: string; // 可选属性 age?: number; constructor(name: string, age?: number) { this.name = name; this.age = age; } } let p = new Person('BNTang'); console.log(p);
在来看看直接定义一个构造函数的情况下,通过对于的类创建出来的对象是什么样子的:
class Person { constructor(name: string, age: number) { } } let p = new Person('BNTang', 18); console.log(p);
参数属性
一句话搞定实例属性的接收和定义
class Person { constructor(public name: string, public age: number) { } } let p = new Person('BNTang', 18); console.log(p);
如上代码类同如下代码:
class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } }
最后
本期结束咱们下次再见👋~
🌊 关注我不迷路,如果本篇文章对你有所帮助,或者你有什么疑问,欢迎在评论区留言,我一般看到都会回复的。大家点赞支持一下哟~ 💗