简体   繁体   English

可以在子类的方法内部使用“ super”来调用相应的父类方法而无需直接引用吗?

[英]Could “super” be used inside a method of subclass to call the corresponding method of super-class without direct referencing?

I came across a usage of "super" in a tutorial that seemed strange. 我在一个看起来很奇怪的教程中遇到了“ super”的用法。 super() is used inside the method get() of the subclass to call the method get() of the superclass without using any accessor notations. 在子类的get()方法内部使用super()来调用超类的get()方法,而无需使用任何访问符。 Would that work? 那行得通吗? If yes, where can I find more references about it? 如果是,我在哪里可以找到更多参考资料?

Edit: 编辑:

class Answer {
  constructor(value) {
    this._val = value;
  }
  get() {
    return this._val;
  }
}

class FirmAnswer extends Answer {
  constructor(value) {
    super(value);
  }

  get() {
    return super() + '!!';
  }
}
var luckyAnswer = new FirmAnswer(7);
luckyAnswer.get();

Thanks @FlexiKling and @sorenymous for typing the code :) 感谢@FlexiKling和@sorenymous键入代码:)

No, direct super calls (without a property) are only allowed in constructors, and constitute syntax errors everywhere else. 不,直接super调用(无属性)仅在构造函数中允许,并且在其他任何地方构成语法错误。 It needs to be super.get() . 它必须是super.get()

The tutorial you are referencing is from 2013. In the earlier versions of the class syntax proposal, this form was indeed possible. 您所参考的教程来自2013年。在早期版本的类语法建议中,确实可以使用这种形式。 However, it was removed in Draft Rev 28 (October 14, 2014 ) : 但是,该草案已在Rev 28草案(2014年10月14日)中删除:

super without an immediately following property specifier is now illegal in all MethodDefinition (no more implicit super using current method name) 现在,在所有MethodDefinition中,没有紧随其后的属性说明符的super都是非法的(不再使用当前方法名隐式的super)

I tested your code and it produced a syntax error. 我测试了您的代码,并产生了语法错误。

class Answer {
  constructor(value) {
    this._val = value;
  }
  get() {
    return this._val;
  }
}

class FirmAnswer extends Answer {
  constructor(value) {
    super(value);
  }

  get() {
    return super() + '!!';
  }
}
var luckyAnswer = new FirmAnswer(7);
luckyAnswer.get();

Console Output: 控制台输出:

Uncaught SyntaxError: 'super' keyword unexpected here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM