js使用类需要使用Babel工具将代码编译成es5或者es3,so 在不支持es6的浏览器中运行的是编译之后的代码。 ts本身可以将代码编译成不同版本标准的代码,编译之后的代码还是es,so ts 真的不是超出js之外的新语言。
- ts中定义类
class Admin {
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
public getName() {
return `${this.x}and${this.y}`;
}
}
const A = new Admin(2, 3);
// tslint:disable-next-line: no-console
console.log(A, A.getName());
- ts 的继承 一个文件中只能定一个类,在tslint 中加入忽略规则
class Mother {
public name: string;
protected like: string;
constructor(name: string, like: string) {
this.name = name;
this.like = like;
}
protected getLike() {
return `你知道我喜欢${this.like}`;
}
}
// 修饰符 public公共 private私有 protected受保护的修饰符
// 如果使用protected修饰父类的构造函数,只能通过子类来创建实例。不能通过父类,在父类的 constructor前加一个protected 之后,测试一下.
const M = new Mother("zhangsan", "running");
console.log(M);
class Daughter extends Mother {
private age: number;
constructor(name: string, age: number, like: string) {
super(name, like);
this.age = age;
// console.log(super.like) // 使用protected修饰,子类的构造函数中只能调用其方法。不可调用属性。
console.log(super.getLike());
}
}
const D = new Daughter("wanghui", 20, "游泳");
console.log(D, D.name);
// console.log(D.age) 你打开这行注释瞧一瞧,一定是红红的 so 私有属性是不可以被 使用的
- 在类中使用readonly
class University {
public readonly name: string;
constructor(name) {
this.name = name;
}
}
const U = new University("北京大学");
console.log(U.name);
// U.name = "北京理工大学" // 就会error
- 5.参数属性
class Position {
// tslint:disable-next-line: no-empty
constructor(public posix: number, prposiy: number) {}
}
const P = new Position(4, 5);
console.log(P);