在javascript对象中覆盖调用

问题描述 投票:0回答:1

我是JavaScript的新手,尝试在没有继承的情况下扩展类变量原型


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

出于某种原因,我无法将

Z
扩展为
B
。然而,
B
类只是一个方法混合和变量包。当我在
prop
上调用一个方法或检索一个
z
时,我是否可以检查它是否可以通过
this.z
访问,如果可以,直接返回

任何有关如何编写此结构的想法都将不胜感激。


我不能直接使用

extend
关键字的原因是
Z
是由库提供的,并且实例是在类上的可调用或静态中构造的。我根本不熟悉
function class constructor
,诸如
_super
__proto__
之类的东西。

为什么我想到这个是因为,您可以在 python 中定义一个 dunder

__call__
__getitem__
来达到这个目的。我不确定这是否可能,如果你能帮我一把,我会很高兴。功能性的东西,例如:

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

但是会申请任何呼叫者或道具检索尝试。


感谢所有评论的建议。 注意以下不是最小的工作示例,而是现实生活中的情况。


/* 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

抱歉我没有找到提供非最小化代码的CDN

javascript inheritance getter-setter
1个回答
0
投票

你可以像这样在原型链中注入

Z
原型:

Object.setPrototypeOf(B.prototype, Z.prototype);

// Library code
class Z{
    constructor() {}
    a()     { console.log('a') }
    get b() { console.log('b') }
    c()     { console.log('c') }
}
const z = new Z();
// End library code

class B{
    constructor() {}
    x()     { console.log('x') }
}

Object.setPrototypeOf(B.prototype, Z.prototype);

let b = new B();
b.a();
b.b;
b.x(); 

z.test = 1;
console.log(b.test); // Undefined (see next snippet)

如果您需要

b
also 可以访问在
z
上设置的任何实例属性(所以不是在它的原型对象上),那么在链中再添加一个步骤,如下所示:

Object.setPrototypeOf(B.prototype, z);

// Library code
class Z{
    constructor() {}
    a()     { console.log('a') }
    get b() { console.log('b') }
    c()     { console.log('c') }
}
const z = new Z();
// End library code

class B{
    constructor() {}
    x()     { console.log('x') }
}

Object.setPrototypeOf(B.prototype, z);

let b = new B();
b.a();
b.b;
b.x(); 

z.test = 1;
console.log(b.test); // 1

© www.soinside.com 2019 - 2024. All rights reserved.