TypeScript Classes All In One
TypeScript Classes All In One
// class Employee {
// constructor(name: string) {
// this.name = name;
// // Property 'name' does not exist on type 'Employee'.ts(2339)
// }
// }
class Employee {
// name: string;
name: string = '';
// age?: number;
age?: number = 0;
constructor(name: string, age?: number) {
this.name = name;
if (age) {
this.age = age;
}
}
greet() {
console.log(`employee name = ${this.name}`);
}
getAge() {
console.log('age =', this.age);
}
}
const em = new Employee('xgqfrms');
em.name;
em.greet();
em.age;
em.getAge();
class Manager extends Employee {
private title: string;
constructor(name: string, title: string) {
super(name);
this.title = title;
}
getTitle() {
console.log('title =', this.title);
}
}
const ma = new Manager('xgqfrms', 'CTO');
// ma.title;
// Property 'title' is private and only accessible within class 'Manager'.ts(2341)
ma.getTitle();
access modifier
访问修饰符: public / private / protected / static
class UFO {
public name: string = '';
private id?: number = 0;
constructor(name: string, id?: number) {
this.name = name;
if (id) {
this.id = id;
}
}
protected getName() {
console.log(`UFO name = ${this.name}`);
}
getId() {
console.log('UFO id =', this.id);
}
getAll() {
this.getName();
this.getId();
}
}
// const ufo = new UFO('ufo', 007);
/*
Octal literals are not allowed in strict mode.ts(1121)
Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '0o7'.ts(1085)
*/
const ufo = new UFO('ufo', 7);
ufo.name;
ufo.getId();
// ufo.getName();
// Property 'getName' is protected and only accessible within class 'UFO' and its subclasses.ts(2445)
ufo.getAll();
const ufo_binary = new UFO('ufo', 0b111);
const ufo_octal = new UFO('ufo', 0o007);
const ufo_hex = new UFO('ufo', 0x007);
class SpaceShip extends UFO {
private uid: string = '2048';
constructor(name: string, id?: number) {
super(name, id);
}
static log(value: any) {
console.log('static value =', value);
}
getUid() {
console.log('private uid =', this.uid);
}
// 改写 getAll
getAll(): void {
this.getName();
this.getId();
// this.getAll();
this.getUid();
}
}
const ss = new SpaceShip('ss', 2022);
ss.name;
// ss.getName();
// Property 'getName' is protected and only accessible within class 'UFO' and its subclasses.ts(2445)
ss.getId();
ss.getUid();
ss.getAll();
refs
https://www.typescriptlang.org/docs/handbook/2/classes.html
https://www.typescriptlang.org/docs/handbook/classes.html
?xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!