Node.js高级对象、高级类

Mixin模式,混合模式,这个是一种不用继承就可以复用的技术,主要还是为了解决多重继承的问题,多重继承的路径是个问题
JS是基于对象的,类和对象都是对象模板
混合mixin,指的是将一个对象的全部或者部分拷贝到另一个对象上去

class Serialization{
    constructor(){
        console.log('Serialization')
        if (typeof(this.stringify)!='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
    }
}
s=new Serialization()
p=new Point(4,5)
    }
}

Node.js高级对象、高级类
父类构造函数中,要求具有属性是stringify的序列化函数,如果没有则抛出异常

class Serialization{
    constructor(){
        console.log('Serialization')
        if (typeof(this.stringify)!='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
    }
    stringify (){
        return `<Point x=${this.x},y=${this.y}>`
    }
}
class Point3D extends Point{
    constructor(x,y,z){
        super(x,y)
        this.z=z
    }
    stringify(){
        return `<Point x=${this.x},y=${this.y},z=${this.z}>`
    }
}
p=new Point(4,5)
console.log(p.stringify())
p3d=new Point3D(7,8,9)
console.log(p3d.stringify())

Node.js高级对象、高级类
高阶对象实现
将类的继承构成箭头函数

class A extends Object{}
// console.log(A)
//匿名类
const A1=class {
    constructor(x){
        this.x=x
    }
}
console.log(A1)
console.log(new A1(100))
console.log(new A1(100).x)
//匿名继承
const B=class extends Object{
    constructor(){
        super()
        console.log('B construtor')
    }
}
console.log(B)
b=new B()
console.log(b)

//箭头函数,参数是类,返回值也是类
//把上例中的Object看成参数
const  x=(Sup)=>{
    return class extends Sup{
        constructor(){
            super()
            console.log('C constructor')
        }
    }
}
const C=Sup=>class extends Sup{
    constructor(){
        super()
        console.log('C constructor')
    }
}
cls=C(A)
console.log(cls)
c=new cls()
console.log(c)

Node.js高级对象、高级类

const Serialization=Sup =>class extends Sup{
    constructor(...args){
        console.log('Serialization constructor')
        super(...args)
        if (typeof(this.stringify)!=='function'){
            throw new ReferenceError('should define stringify')
        }
    }
}

class Point{
    constructor(x,y){
        console.log('point constructor')
        this.x=x
        this.y=y
    }
}
class Point3D extends Serialization(Point){
    constructor(x,y,z){
        super(x,y)
        this.z=z
    }
    stringify(){
        return `<Point3d ${this.x},${this.y}>`
    }
}
let p3d=new Point3D(70,80,90)
console.log(p3d.stringify())

Node.js高级对象、高级类
注意:
Serialization(Point)这一步实际上是一个匿名箭头函数调用,返回了一个新的类型,Point3D继承自这个新的匿名类型,增强了功能

上一篇:javascript-解析一个Bundle,它是Remotemessage中的JSONString到JSON对象


下一篇:数组对象去重复