Search code examples
javascriptinheritanceprototypesuperextends

Overwrite call in javascript object


I am a newbie in JavaScript, trying to extend class variable prototype without inheritance


class Z{
    constructor(){}
    a(){console.log('a')}
    get b(){console.log('b')}
    c(){console.log('c')}
}

class B{
    constructor(z){
        this.z = z;
    }
}

let z = new Z();
let b = new B(z);
b.a(); // error
b.b; // error

the B class is intended to be just a method mixin and variable bundle, however for some reason, I cannot extend Z to B. When I calling a method, or retrieve a prop on z, can I inspect whether it can be accessed through this.z, if so, return it directly?

Any ideas of how to write this structure will be more than appreciated.


The reason I cannot use extend keyword directly, is that Z is provided by a lib, and the instance is constructed in a callable, or static on class. I am not familiar with function class constructor at all, things such as _super or __proto__.

And why I thought about this is that, you can define a dunder __call__ or __getitem__ in python to serve this purpose. I am not sure if it is possible at all, I will be so glad if you can give me a hand. Something functional like:

class Z{
  a()
    try{
      return this.z.a()
    }catch(){/}
  }
}

But would apply for any retrieving attempt.


Thanks all comments for suggestion. Note following are not minimum working example but real life occasion.


/* lib source code */
function fromTextArea(textarea, options) {
  options = options ? copyObj(options) : {};
  options.value = textarea.value;
  if (!options.tabindex && textarea.tabIndex) { options.tabindex = textarea.tabIndex; }
  if (!options.placeholder && textarea.placeholder) { options.placeholder = textarea.placeholder; }
  // Set autofocus to true if this textarea is focused, or if it has
  // autofocus and no other element is focused.
  if (options.autofocus == null) {
    var hasFocus = activeElt();
    options.autofocus = hasFocus == textarea ||
      textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  }

  function save() { textarea.value = cm.getValue(); }

  var realSubmit;
  if (textarea.form) {
    on(textarea.form, "submit", save);
    // Deplorable hack to make the submit method do the right thing.
    if (!options.leaveSubmitMethodAlone) {
      var form = textarea.form;
      realSubmit = form.submit;
      try {
        var wrappedSubmit = form.submit = function () {
          save();
          form.submit = realSubmit;
          form.submit();
          form.submit = wrappedSubmit;
        };
      } catch (e) { }
    }
  }

  options.finishInit = function (cm) {
    cm.save = save;
    cm.getTextArea = function () { return textarea; };
    cm.toTextArea = function () {
      cm.toTextArea = isNaN; // Prevent this from being ran twice
      save();
      textarea.parentNode.removeChild(cm.getWrapperElement());
      textarea.style.display = "";
      if (textarea.form) {
        off(textarea.form, "submit", save);
        if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") { textarea.form.submit = realSubmit; }
      }
    };
  };

  textarea.style.display = "none";
  var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
    options);
  return cm
}

// a part of the application I am working on
class CodeEditor{
    constructor(
        container, 
        generic, 
        types, 
        modes, 
        options, 
    ){
        this.generic = generic;
        this.types = types;
        this.modes = modes;

        /*
        .code-container
            .cm-header-bar
                .cm-code-compile-wrapper
                button.dropdown-button
            textarea
        */
        this.container = container;
        this.textarea = container.querySelector('textarea');
        this.header = this.container.querySelector('.cm-header-bar');
        this.compileBtnWrapper = this.header.querySelector('.cm-code-compile-wrapper');
        this.compileBtn = document.createElement('div');
        this.compileBtn.classList.add('cm-code-compile');
        this.compileBtn.innerText = 'compile';
        this.options = options;

        this.mode = this.textarea.getAttribute('id');
        this.options.mode.name = this.mode;
        this.editor = CodeMirror.fromTextArea(this.textarea, this.options);
        // editor setup
        this.editor.on("gutterClick", function(cm, n) {
            let info = cm.lineInfo(n);
            cm.setGutterMarker(n, "breakpoints", info.gutterMarkers ? null : makeMarker());
        });
        // compilable
        if(this.mode !== this.generic)this.compilable();
        this.dropdown = dropdown(this.header.querySelector('.dropdown-button'), '预先处理', generic);
        Object.keys(this.modes).forEach(mode=>{
            this.dropdown.addOption(mode, ()=>{
                htmlEditor.setOption('mode', { name: this.name, globalVars: true });
                this.mode = mode;
                this.editor.refresh();
                play();
                if(mode !== this.generic)this.compilable();
            }, mode === this.mode);
        });
    }

    get name(){
        return this.types[this.mode];
    }

    compilable(){
        this.compileBtnWrapper.appendChild(this.compileBtn);
        let temp = {};
        const oxidize = () => {
            this.compileBtn.onclick = () => {
                temp.code = this.getValue();
                temp.mode = this.mode ;
                // compile
                this.dropdown.onOption(this.generic);
                this.setValue(this.modes[this.mode]());
                this.options.mode.name = this.types[this.generic];
                this.setOption('mode', this.options.mode);
                this.compileBtn.classList.add('active');
                this.compileBtn.innerText = 'restore';
                // undo
                reduce();
            }
        }
        const reduce = () => {
            this.compileBtn.onclick = () => {
                this.dropdown.onOption(temp.mode);
                this.setValue(temp.code);
                this.options.mode.name = temp.mode;
                this.setOption('mode', this.types[temp.mode]);
                this.compileBtn.classList.remove('active');
                this.compileBtn.innerText = 'compile';
                // undo
                oxidize();
            }
        }
        oxidize();
    }

    /* 
    I am optimizing a big proj, the instance used to be a 
    CodeMirror. However, it produces a lot of redundant 
    self-occurring parts, and I do not want to pass parameters
    all day, therefore I wrapped it with a CodeEditor instance
    However, other code in this project would call the CodeMirror 
    prototype method, since I cannot find a way to extends 
    CodeMirror methods from this.editor to this, I need to 
    redefine them all (following are only a tiny part)
    */
    setValue(v){return this.editor.setValue(v)}
    getValue(){return this.editor.getValue()}
    setOption(...args){return this.editor.setOption(...args)};
    focus(){return this.editor.focus()}

    // more functionality
    compiled(){return this.modes[this.mode]() || ''};
    raw(){return this.getValue().trimEnd()}
}

CodeMirror 5.63.3: https://codemirror.net/5/doc/releases.html

Sorry that I did not find a CDN that provides non-minimised code.


Solution

  • Unfortunately, javascript doesn't provide getattr like in python, so your best bet is to create proxy methods manually, for example:

    class B {
        constructor(z) {
            let proto = Object.getPrototypeOf(z)
            for (let p of Object.getOwnPropertyNames(proto)) {
                let val = proto[p]
                if (typeof val === 'function')
                    this[p] = val.bind(z)
            }
        }
    }
    

    Note that val.bind(z) would invoke Z methods in the context of the passed z object (="facade"). You can also do val.bind(this), which would use the B object as a context (="mixin").