代码之家  ›  专栏  ›  技术社区  ›  Deepak Dixit

在JavaScript中,当子类使用“super”来调用父方法时,为什么父类使用子类对象来调用任何函数?

  •  0
  • Deepak Dixit  · 技术社区  · 6 年前

    这里是子类对象调用 super.msg1() 也就是说这次通话 Parent's msg1() 父级的msg1() 调用另一个函数 msg2() 我是说,属于自己的阶级 Parent's msg2()

    所以在这种情况下,函数的直接调用和间接调用都应该使用父类的定义,这在这里是不发生的。

    使用 super Parent 类方法,在当前示例中,调用 msg2() 是的一部分 msg1()

    Message 1 from Parent class
    Message 2 from Child class
    

    但我期待着

    Message 1 from Parent class
    Message 2 from Parent class
    

    class Parent {
        msg1() {
          console.log('Message 1 from Parent class')
          this.msg2();
        }
    
        msg2() {
          console.log('Message 2 from Parent class')
        }
      }
    
      class Child extends Parent {
    
        constructor() {
          super();
        }
    
        msg1() {
          super.msg1();
        }
    
        msg2() {
          console.log('Message 2 from Child class')
        }
      }
    
      ch = new Child();
      ch.msg1();

    是否有任何方法可以在不修改父类的情况下获得预期的输出。

    0 回复  |  直到 6 年前
        1
  •  1
  •   Niklas E.    6 年前

    你所观察到的完全是意料之中的。看到了吗 https://javascript.info/class-inheritance

    super 他总是打电话来 “父”类方法。但是你的日志 "Message 2 from Child class" this.msg2() 在父类中。你不知道或奇怪的是 this 实例与子类中的实例保持相同,因此父类内部方法范围中的方法也被覆盖。这在所有面向对象的语言中都是完全可以预期的。

    编辑: 如果您想要这些属性,您必须使用一个“技巧”,在其中添加一个具有原始功能的附加方法,这样您就可以在父类中决定调用原始功能还是(可能)扩展功能。

    class Parent {
        msg1() {
          console.log('Message 1 from Parent class')
          // call basic functionality directly, to avoid use of override method
          this._msg2basic();
        }
    
        // Redirect call
        msg2(...args) {
          this._msg2(...args)
        }
    
        // Basic msg2 functionality of the parent that could be needed if overwrite.
        // Usually with a underscore _ to indicate it's private and not intended for "outside" usage.
        _msg2basic() {
          console.log('Message 2 from Parent class')
        }
      }
    
      class Child extends Parent {
    
        constructor() {
          super();
        }
    
        msg1() {
          super.msg1();
        }
    
        // Override parent msg2
        msg2() {
          console.log('Message 2 from Child class')
        }
      }
    
      ch = new Child();
      console.log('ch.msg1()')
      ch.msg1();
      console.log('ch.msg2()')
      ch.msg2();

    推荐文章