【问题标题】:How to avoid doing inheritance如何避免继承
【发布时间】:2019-02-04 03:35:55
【问题描述】:

我有一个名为 a 的对象,我几乎一直在使用它。

然后 'b' 出现了尴尬,我需要在调用 notify 之前做一些其他的事情。

在面向对象中调用父对象的最佳功能/原型方法是什么?

let a = {};

a.notify = () => {
    doSomethingCool();
}

var b = Object.create(a);

b.notify = () => {
    doCoolStuffFirst();
    doSomethingCool();
}

【问题讨论】:

标签: javascript


【解决方案1】:

不太清楚你在问什么。你只是在寻找

const notify_orig = b.notify;
b.notify = () => {
    doCoolStuffFirst();
    notify_orig.call(b);
}

?

【讨论】:

    【解决方案2】:

    正如你所说,使用类很容易:

    class A {
      notify() {
        doSomethingCool();
      }
    }
    
    class B {
      notify() {
        doCoolStuffFirst();
        super.notify();
      }
    }
    

    如果没有 ES6 类,您将陷入困境。 ES6 编译器将super.notify() 翻译成类似

    _get(
       B.prototype.__proto__ ||
       Object.getPrototypeOf(B.prototype),
       "notify", this
    ).call(this);
    

    _get 是一种巨大的实用方法,可以平滑不同类型的值和继承等方面的粗糙边缘)。这不是不可能,只是太复杂了,你可能不想自己做。

    【讨论】:

      【解决方案3】:

      不使用__proto__class(这是ES6 中的语法糖)。

      function doSomethingCool() {
          console.log("something cool");
      }
      
      function doCoolStuffFirst() {
          console.log("cool stuff first");
      }
      
      let a = {};
      a.notify = () => {
          doSomethingCool();
      }
      a.notify();
      
      let b = Object.create(a)
      b.notify = (() => {
          let notifySuper = b.notify; // reference to the 'super' method
          return () => {
              doCoolStuffFirst();
              notifySuper();
          }
      })();
      b.notify();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-13
        • 1970-01-01
        • 1970-01-01
        • 2021-04-26
        • 1970-01-01
        • 2020-02-04
        • 1970-01-01
        • 2011-04-14
        相关资源
        最近更新 更多