Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>super() with mixins</title>
</head>
<body>
<script>
  "use strict";
  console.clear();
  
  class Base {
    method() {
      console.log("Base method");
    }
  }
  
  class Mixin {
    method() {
      console.log("Mixin method");
      
      // We want this to call Base.prototype.method
      super.method();
    }
  }
  
  // Will mix Mixin into Base, overwriting the existing definition of method().
  mixin(Base, Mixin);
  
  var instance = new Base();
  instance.method(); // will super work, calling back into Base's original version?
                     // check the console for an answer!
  
  function mixin(Base, Mixin) {
    // Home needs to be an object whose [[Prototype]] contains the original methods.
    // copyMethods(Base.prototype) gives us an object with the methods; then
    // Object.create it to get the extra level of prototype.
    const newHome = Object.create(copyMethods(Base.prototype));
    for (const name of Object.getOwnPropertyNames(Mixin.prototype)) {
      const desc = Object.getOwnPropertyDescriptor(Mixin.prototype, name);
      if (typeof desc.value === "function") {
        desc.value = desc.value.toMethod(newHome);
      }
      
      // TODO getters/setters
      
      Object.defineProperty(Base.prototype, name, desc);
    }
    
    // TODO class-side inheritance as well
  }
  
  function copyMethods(source) {
    var copy = Object.create(Object.getPrototypeOf(source));
    for (const name of Object.getOwnPropertyNames(source)) {
      const desc = Object.getOwnPropertyDescriptor(source, name);
      if (typeof desc.value === "function") {
        Object.defineProperty(copy, name, desc);
      }
    }
    
    return copy;
  }
</script>
</body>
</html>
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
domenicpro
0viewers