TypeScript前端学习(四)
2023-12-26 13:56:38
前言
????????还是分享的笔记,大佬请绕行!
一、类的定义和继承
console.log("----对象---");
var people = {
"name": "张三",
syaHi() {
console.log("HI,my name is " + this.name);
}
}
people.syaHi();
console.log("----类---");
class People {
name: string;
constructor(name: string) {
this.name = name;
}
syaHi() {
console.log("HI,my name is " + this.name);
}
}
//实例化类
var people2 = new People("李四");
people2.syaHi();
console.log("----类的继承---");
//类的继承
class Student extends People {
constructor(name: string) {
super(name);
}
syaHi() {
console.log("HI,my name is " + this.name);
}
makeWorks() {
console.log("我在做作业");
}
}
var student = new Student("小明");
student.syaHi() + "," + student.makeWorks();
class Teacher extends People {
subject: string;
constructor(name: string, subject: string) {
super(name);
this.subject = subject;
}
syaHi() {
super.syaHi();
console.log("同学们好");
}
teach() {
console.log(this.name + ",我在教" + this.subject);
}
}
var teacher = new Teacher("李老师", "数学");
teacher.syaHi();
console.log("----------")
teacher.teach();
示例效果
二、类的访问权限
console.log("----类的访问权限---");
class Animal {
//private className:string="Animal"; //私有属性,只能在类内部访问(继承他的类用就会报错了)
className: string = "Animal";
protected constructor() {
this.className = "Animal"; //受保护的构造函数,只能在类内部访问(继承他的类用就会报错了)
}
}
//var animal = new Animal(); //TS2674: Constructor of class Animal is protected and only accessible within the class declaration.
class Dog extends Animal {
name: string;
constructor(name: string) {
super();
this.name = name;
}
run() {
console.log(this.name + "在跑");
}
}
var dog = new Dog("小狗");
dog.run();
示例运行效果
注释的语句,报错描述写在注释里了
报错就是因为设置了protected等关键字
三、只读属性与存取器
console.log("----只读属性---")
//
class Circle {
readonly PI: number = 3.14;
readonly r: number;
constructor(r: number) {
this.r = r;
}
getArea() {
return this.PI * this.r * this.r;
}
}
var circle = new Circle(10);
console.log(circle.getArea());
//circle.r = 20; //TS2540: Cannot assign to 'r' because it is a read-only property.
console.log("----存取器---");
class Circle2 {
readonly PI: number = 3.14;
protected r: number = 0;
set R(r: number) {
if (r < 0) {
return;
}
this.r = r;
}
get R(): number {
return this.r;
}
getArea() {
return this.PI * this.r * this.r;
}
}
var circle2 = new Circle2();
circle2.R = 10;
console.log(circle2.R);
console.log(circle2.getArea());
示例运行效果
总结
- 看起来跟其他面向对象的后端语言真像
- 这次没有用tsc命令生成js对比,有兴趣的可以自己生成对比看看
纯粹的笔记备忘,uping!
文章来源:https://blog.csdn.net/zwrlj527/article/details/135218568
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!