Mixin模式,混合模式。这是一种不用继承就可以复用的技术。主要还是为了解决多重继承的问题。多继承的继承路径是个问题。
JS是基于对象的,类和对象都是对象模板。混合mixin,指的是将一个对象的全部或者部分拷贝到另一个对象上去。其实就是属性了。
可以将多个类或对象混合成一个类或对象。
继承实现
先看一个继承实现的例子
class Serialization {
constructor() {
console.log("Serialization construtor ~~~~~~")
if (typeof(this.stringfy) !== "function") {
throw new ReferenceError("should define stringify.");
}
}
}
class Point extends Serialization {
constructor(x, y) {
console.log("Point Constructor");
super(); // 调用父构造器
this.x = x;
this.y = y;
}
stringfy() {
return `<Point x="${this.x}, y=${this.y}">`;
}
}
s = new Serialization(); // 构造Serialization失败
p = new Point(4,5); // 构造子类对象时,调用父类构造器执行也会失败
父类构造函数中,要求具有属性是stringify的序列化函数,如果没有则抛出异常。
以下是完整继承的代码
class Serialization {
constructor() {
console.log("Serialization construtor ~~~~~~")
if (typeof(this.stringfy) !== "function") {
throw new ReferenceError("should define stringify.");
}
}
}
class Point extends Serialization {
constructor(x, y) {
console.log("Point Constructor");
super(); // 调用父构造器
this.x = x;
this.y = y;
}
stringfy() {
return `<Point x="${this.x}, y=${this.y}">`;
}
}
class Point3D extends Point {
constructor(x, y, z) {
super(x, y); // 调用父构造器
this.z = z;
}
stringfy() {
return `<Point3D x="${this.x}, y=${this.y}, z=${this.z}">`
}
}
p = new Point(4, 5);
console.log(p.stringfy());
console.log("=====================");
p3d = new Point3D(7, 8, 9);
console.log(p3d.stringfy());
/* 输出结果
Point Constructor
Serialization construtor ~~~~~~
<Point x="4, y=5">
=====================
Point Constructor
Serialization construtor ~~~~~~
<Point3D x="7, y=8, z=9">
*/
高阶对象实现
将类的继承构建成箭头函数。
const Serialization = Sup => class extends Sup{
constructor(...args){
console.log("Serialization constructor");
super(...args);
if (typeof this.stringfy !== "function"){
throw ReferenceError("Stringfy is not define.");
}
}
};
class Point{
constructor(x, y){
console.log("Point sonctructor");
this.x = x;
this.y = y;
}
}
class Point3D extends Serialization(Point){
constructor(x, y, z){
super(x, y);
this.z = z;
}
stringfy(){
console.log(`<Point ${this.x}.${this.y}.${this.z}>`)
}
}
let p3d = new Point3D(3, 4, 5);
p3d.stringfy();
/* 输出结果
Serialization constructor
Point sonctructor
<Point 3.4.5>
*/
网友评论