????????还是分享的笔记,大佬请绕行!
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());
示例运行效果