class Person {
constructor(name, age) {
this.name = name;
this.age = age
}
sayName(){
console.log(`age is ${this.age}, name is ${this.name}`);
}
log() {
console.log(`I am ${this.name},age is ${this.age}`);
}
}
class Man extends Person {
constructor(name, age) {
super(name, age);
this.gender = 'man';
}
sayName() {
console.log(`I am a ${this.gender},age is ${this.age}, name is ${this.name}`);
}
}
let bob = new Man('Bob', 2);
bob.sayName();
bob.log('coo', 3)
typescript写法
class Person{
name:string;//需要指明属性类型
age: number;
constructor(name:string,age: number){//需要指明参数类型
this.name = name;
this.age = age;
}
sayName(){
console.log(`I am ${this.name}, age of ${this.age}`);
}
}
class Man extends Person{
gender:string; //需要提前声明gender属性的类型
constructor(name:string){//传入的参数需要指明类型
super(name, age);
this.gender = 'man';
}
sayName(){
console.log(`I am a ${this.gender} , name is ${this.name},age of ${this.age}`);//可以使用ES6模板语法
}
}
let bob = new Man('Bob',2);
bob.sayName();//I am a man, name is Bob, age of 2