tc39 / proposal-mixins

A template for ECMAScript proposals
MIT License
61 stars 2 forks source link

Mixin reflection? #10

Open dead-claudia opened 4 years ago

dead-claudia commented 4 years ago

It might be useful to know what mixins are applied to a class or object.

// Usually, you'll call this one of two ways:
// 1. `Object.getMixins(Object.getPrototypeOf(instance))`
// 2. `Object.getMixins(Class.prototype)`
Object.getMixins = object => {
    let list = []
    while (
        (object = Object.getPrototypeOf(object)) != null &&
        Reflect.hasOwnProperty(object, Symbol.mixin)
    ) {
        list.push(object[Symbol.mixin])
    }
    return list
}

Also, mixins should all implement Symbol.hasInstance as follows, so object instanceof Mixin is still somewhat meaningful even as it doesn't directly inherit from it:

Mixin[Symbol.hasInstance] = object => {
    while ((object = Object.getPrototypeOf(object)) != null) {
        if (Reflect.hasOwnProperty(object, Symbol.mixin)) {
            if (object[Symbol.mixin] === Mixin) return true
        }
    }
    return false
}