一:类
class Point{
//构造函数
constructor(x,y) {
this.x = x;
this.y = y;
}
toString(){
return '点的位置:(' + this.x + ',' + this.y + ')'
}
}
let p = new Point(1,2);
console.log(p.toString());
![](https://img.haomeiwen.com/i15616481/f5c40b13415db21e.png)
二、静态方法
![](https://img.haomeiwen.com/i15616481/397f815ae6c206da.png)
class MyDate{
static validateMonth(month){
month = Number.parseInt(month);
return month >= 1 && month <=12;
}
}
console.log(MyDate.validateMonth(12));
![](https://img.haomeiwen.com/i15616481/db2594d2104adff6.png)
三、继承
3-1:继承的使用
![](https://img.haomeiwen.com/i15616481/88faa711bac179ac.png)
class Animal {
constructor(name,age) {
this.name = name;
this.age = age;
}
eat(){
return "Food";
}
showInfo(){
console.log("动物的信息:名称" + this.name + ",年龄" + this.age);
}
}
//继承
class Cat extends Animal {
constructor(name,age,color) {
super(name,age);
this.color = color;
}
}
let cat = new Cat('小黑',3,'black');
cat.showInfo();
let animal = new Animal("小黄",5);
animal.showInfo();
let food = animal.eat();
console.log(food);
![](https://img.haomeiwen.com/i15616481/0e681bccea827397.png)
3-2:重写父类方法demo1
class Animal {
constructor(name,age) {
this.name = name;
this.age = age;
}
eat(){
return "Food";
}
showInfo(){
console.log("动物的信息:名称" + this.name + ",年龄" + this.age);
}
}
//继承
class Cat extends Animal {
constructor(name,age,color) {
super(name,age);
this.color = color;
}
// 重写showInfo方法
showInfo(){
console.log("毛的信息:名称" + this.name + ",年龄" + this.age + ",毛色" + this.color);
}
}
let cat = new Cat('小黑',3,'black');
cat.showInfo();
let animal = new Animal("小黄",5);
animal.showInfo();
let food = animal.eat();
console.log(food);
![](https://img.haomeiwen.com/i15616481/122d677c68113683.png)
demo2
class Animal {
constructor(name,age) {
this.name = name;
this.age = age;
}
eat(){
return "Food";
}
showInfo(){
console.log("动物的信息:名称" + this.name + ",年龄" + this.age);
}
}
//继承
class Cat extends Animal {
constructor(name,age,color) {
super(name,age);
this.color = color;
}
eat() {
//调用父类的方法
let result = super.eat();
console.log("来自父类:",result);
return result + "fish"
}
// 重写showInfo方法
showInfo(){
console.log("毛的信息:名称" + this.name + ",年龄" + this.age + ",毛色" + this.color);
}
}
let cat = new Cat('小黑',3,'black');
cat.showInfo();
let foods = cat.eat();
console.log(foods);
let animal = new Animal("小黄",5);
animal.showInfo();
let food = animal.eat();
console.log(food);
![](https://img.haomeiwen.com/i15616481/31f2eb706b489e6d.png)
网友评论