类的修饰符
继续昨天的知识点,class类
总共有三个 public private protected
使用public 修饰符 可以让你定义的变量 内部访问 也可以外部访问 如果不写默认就是public
class Person{
public name: string
age: number
color:string
constructor(name,age){
this.name = name
this.age = age
this.color = color
}
run() {
}
}
let people = new Person('wang',18,'red')
people.name
使用 private 修饰符 代表定义的变量私有的只能在内部访问 不能在外部访问
class Person{
public name: string
private age: number
color:string
constructor(name,age){
this.name = name
this.age = age
this.color = color
}
run() {
}
}
let people = new Person('wang',18,'red')
people.age // 这样会报错,不能这样写
使用 protected 修饰符 代表定义的变量私有的只能在内部和继承的子类中访问 不能在外部访问
class Person {
public name:string
private age:number
protected color:string
constructor (name:string,ages:number,some:string) {
this.name = name
this.age = ages
this.color = color
}
run () {
}
}
class Man extends Person{
constructor () {
super("wang",18,'red')
console.log(this.color)
}
create () {
console.log(this.color)
}
}
let people = new Person('wang',18,'red')
let man = new Man()
man.color
static 静态属性 和 静态方法
我们用static 定义的属性 不可以通过this 去访问 只能通过类名去调用
class Person{
public name: string
private age: number
static color:string
constructor(name,age){
this.name = name
this.age = age
this.color = color // 这样会报错
}
run() {
}
}
Person.color // 这样没有问题
static 静态函数 同样也是不能通过this 去调用 也是通过类名去调用,如果两个函数都是static 静态的是可以通过this互相调用。
interface 定义 类
interface 定义类 使用关键字 implements 后面跟interface的名字多个用逗号隔开 继承还是用extends
interface PersonClass {
get(type: boolean): boolean
}
interface PersonClass2{
set():void,
asd:string
}
class A {
name: string
constructor() {
this.name = "123"
}
}
class Person extends A implements PersonClass,PersonClass2 {
asd: string
constructor() {
super()
this.asd = '123'
}
get(type:boolean) {
return type
}
set () {
}
}