Class语法

一、Class语法:
Class在语法上更加贴合面向对象的写法;Class实现继承更易读、易理解;本质是语法糖,使用了prototype。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ class Mathhandle{
constructor(x,y){
this.x = x;
this.y = y;
}
add(){
return this.x + this.y
}
}
const mm = new Mathhandle(1,2);
console.log(mm.add());

typeof Mathhandle //function
console.log(Mathhandle === Mathhandle.prototype.constructor); // true

二、Class继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Animal{
constructor(name){
this.name = name;
}
eat(){
console.log(this.name + 'eat')
}
}

class Dog extend Animal{
constructor(name){
super(name)
this.name = name;
}
say(){
console.log(`${this.name} eat`)
}
const dog = new Dog('hashiqi');
dog.say();
dog.eat();
}
文章目录
本站访客数人次