在ES6中,class (类)作为对象的模板被引入,可以通过 class 关键字定义类。
class 的本质是 function。
它可以看作一个语法糖,让对象原型的写法更加清晰、更像面向对象编程的语法。
基础用法
类定义
// es5造类 function Person(name,age) { this.name = name; this.age = age; } Person.prototype.sayName = function() { return this.name; } let p1 = new Person('小马哥',28); console.log(p1); // es6造类 class Person { // 实例化的时候会立即被调用 constructor(name, age) { this.name = name; this.age = age; } }
类的继承 extends
class Animal{
constructor(name,age) {
this.name = name;
this.age = age;
}
sayName(){
return this.name;
}
sayAge(){
return this.age;
}
}
class Dog extends Animal{
constructor(name,age,color) {
super(name,age);
// Animal.call(this,name,age);
this.color = color;
}
// 子类自己的方法
sayColor(){
return `${this.name}是${this.age}岁了,它的颜色是${this.color}`
}
// 重写父类的方法
sayName(){
return this.name + super.sayAge() + this.color;
}
}
let d1 = new Dog('小黄',28,'red');
console.log(d1.sayColor());
console.log(d1.sayName());

浙公网安备 33010602011771号