这是我参与更文挑战的第12天,活动详情查看: 更文挑战
一、类的修饰符
1. 定义:
在Typescirpt中类的修饰符有public、private和protected这三个修饰符,接下来看一看这三个修饰符的说明:
- public修饰的属性或方法是共有的,可以再任何地方访问到,默认的所有属性或者方法都public
- private修饰的属性或者方法是私有的,不能再它的类外面访问,只能在本内部访问使用
- protected修饰的属性或者方法是受保护的,它和private类似,唯一的区别是可以再继承的类中访问,比如父类的protected成员成为子类的protected成员,只允许子类成员的访问。
例子
- 定义一个类,测试三个修饰符属性
class Person {
// 不带修饰符默认就是public
name: '张三'
private age: 18
protected gender: '男'
info() {
console.log(`姓名: ${this.name} 年龄: ${this.age} 性别: ${this.gender}`);
}
}
let person1 = new Person()
console.log(person1.name);
console.log(person1.age);
person1.info
结果:new出的对象,只能访问public修饰的,而类的内部三种修饰符都和访问
class Person {
// 不带修饰符默认就是public
name = '张三'
private age= 18
protected gender= '男'
info() {
console.log(`姓名: ${this.name} 年龄: ${this.age} 性别: ${this.gender}`);
}
}
let person1 = new Person()
console.log(person1.name);
// console.log(person1.age);
person1.info()
- 定义一个类, 测试protect属性
class Father {
// 不带修饰符默认就是public
name = '张三'
private age= 18
protected gender= '男'
info() {
console.log(`姓名: ${this.name} 年龄: ${this.age} 性别: ${this.gender}`);
}
}
class children extends Father {
callParent() {
console.log(this.gender);
}
}
let child = new children()
child.callParent()
二、接口约束类
在面向对象编程中,接口是一种规范的定义,他定义了行为和动作规范,在大型项目中通常采用面向对象的编程思路,那么就要用到接口约束类,实现高内聚低耦合的代码规范。
- 例子: 定义一个接口规范, 然后类去实现它里面所有的方法和属性
interface ISuperMan {
name: string;
age: number;
fly: Function;
}
class superMan implements ISuperMan {
name:string = '张三';
age:number = 18;
fly() {
console.log(this.name);
}
}
let superManInstance = new superMan()
superManInstance.fly()
- 例子:接口的多实现
interface ISuperMan {
name: string;
age: number;
fly: Function;
}
interface IIronMan {
eat:Function;
}
interface ISpiderMan {
run:Function;
}
class superMan implements ISuperMan , IIronMan , ISpiderMan {
name:string = '张三';
age:number = 18;
fly() {
console.log(this.name);
}
eat() {
console.log('吃饭');
}
run() {
console.log('跑步');
}
}
let superManInstance = new superMan()
superManInstance.fly()
superManInstance.eat()
superManInstance.run()
- 例子: 接口的多继承, 类实现多个接口太过麻烦, 用一个接口继承多个接口, 然后再用类去实现这个继承多个接口的接口
interface ISuperMan {
name: string;
age: number;
fly: Function;
}
interface IIronMan {
eat:Function;
}
interface ISpiderMan {
run:Function;
}
interface Iman extends ISuperMan, IIronMan ,ISpiderMan {}
class superMan implements Iman {
name:string = '张三';
age:number = 18;
fly() {
console.log(this.name);
}
eat() {
console.log('吃饭');
}
run() {
console.log('跑步');
}
}
let superManInstance = new superMan()
superManInstance.fly()
superManInstance.eat()
superManInstance.run()