持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第10天,点击查看活动详情
1.基础使用语法
ts中的class ,不仅提供class语法,也是一种类型的存在
class Person{} //1.创建类
const p=new Person() //2.创建实例
2.添加实例属性
写法:1.属性: 属性类型 2.属性:值
class Person{
age:number,
gender='男',
}
3.添加实例方法
方法的类型注解(参数和返回值)和函数用法相同
class Point{
x=1,
y=2,
sum(n:number):viod{
this.x *=n;
this.y *=y;
}
}
const p=new Point()
p.sum(10)
4.构造函数 construtor
构造函数是为类的属性设置初始值
1.成员初始化后(比如:age:number),才可以通过this(实例) this.age来访问实例成员
2.需要为构造函数指定类型注解,否则会被隐私推断为any;
比如 construtor(age:number,gender ) 此时gender为any
3.构造函数不需要返回值类型
class Person{
age:number,
gender='男',
construtor(age:number,gender:number){
this.age=age
this.gender=gender
}
}
5.继承extends,implements
类继承的两种方式 1.extends 继承父类 2.implements 实现接口(就是继承接口)ts特有的
1.通过extends关键字实现继承 (类和类之间的关系) 解释:子类Dog 继承父类Animal,Dog的实例就同时有了父类和子类的所有属性和方法
class Animal{
move(){
console.log('1')
}
}
class Dog extends Animal{
name="sss"
eat(){
console.log('sss')
}
}
const dog=new Dog()
dog.move();
dog.eat();
2.通过implements关键字让class实现接口 (类和接口之间的关系) 解释:Person 类实现接口Singable 意味着,Person类中必须提供Singable 接口中指定的所有方法和属性 相当于 Person类实现接口 添加了约束
interface Singable{
sing():void
name:string
}
class Person implements Singable{
name:string
sing(){
console.log(www)
}
}
6.可见性修饰符 public,protected,private
可先性修饰符可以控制class的方法和属性 对于class外的代码是否可见
写法:在类属性和方法前面添加关键字
public:公有的,公有成员可以被任何地方访问,默认可见性,可以直接省略不写
class Animal{
public move(){
console.log('走两步')
}
}
class Dog extends Animal{
name="sss"
}
const dog=new Dog()
dog.move(); //可以被访问
protected:受保护的,仅对其声明在类和子类中可见 通过this来访问;但是对实例对象不可见
class Animal{
protected move(){
console.log('走两步')
}
eat(){
this.move() // 可以访问
}
}
class Dog extends Animal{
eat(){
this.move() //可以访问
}
}
const dog=new Dog()
dog.move(); //不可以被访问
private:私有的,只在当前类中可见使用, 对子类和实例对象不可见
class Animal{
private move(){
console.log('走两步')
}
eat(){
this.move() //可以访问
}
}
class Dog extends Animal{
name="sss"
eat(){
this.move() //不可以访问
console.log('sss')
}
}
const dog=new Dog()
dog.move(); //不可以被访问
结束语
希望大家能够喜欢我的文章,我真的很用心在写,也希望通过文章认识更多志同道合的朋友。
最后伙伴们,如果喜欢我的可以给点一个小小的赞👍或者关注➕都是对我最大的支持。