类的用法
es5造类
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.getName = function () {
return this.name;
};
let p = new Person('tom', 20);
console.log(p.getName());//tom
难以理解。
es6引入class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
getName() {
return this.name;
}
getAge() {
return this.age;
}
}
// 通过Object.assign()方法一次性向类中添加多个方法
/*Object.assign(Person.prototype, {
getName() {
return this.name;
},
getAge() {
return this.age;
}
});*/
let p = new Person('tom', 20);
console.log(p.getName(), p.getAge());//tom 20
类的继承
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
getName() {
return this.name;
}
getAge() {
return this.age;
}
}
class Cat extends Animal {
constructor(name, age, color) {
super(name, age);// 相当于Animal.call(this, name, age);,但是写的时候不能这么写
this.color = color;
}
//子类自己的方法
getColor() {
return this.color;
}
//重写父类的方法
getName() {
return `${this.name}今年${this.age}岁,它的颜色是${this.color}的`
}
}
let c = new Cat('tom', 3, '灰色');
//继承父类
console.log(c.getAge());//3
//自己的
console.log(c.getColor());//灰色
//重写父类方法
console.log(c.getName());//tom今年3岁,它的颜色是灰色的
注意: 子类继承父类时,构造方法中一定要写super()。
Mixin(混入)模式
Mixin模式指的是,将多个类的接口“混入”(mix in)另一个类。它在ES6的实现如下:
class DistributedEdit extends mix(Loggable, Serializable) {
// ...
}