简体   繁体   English

Javascript-通过原型访问“ super”关键字

[英]Javascript - Get access to 'super' keyword via prototype

I want to override a class method via the prototype property, but I'm not able to access the 'super' keyword. 我想通过prototype属性重写类方法,但是我无法访问'super'关键字。

class A {
    foo(){
        console.log('foo-foo');
    }
}

class B extends A {}

B.prototype.foo = function(){ super.foo() }
// Uncaught SyntaxError: 'super' keyword unexpected here

// what I want:
const b = new B();
b.foo(); // foo-foo

The motivation here is to import the new b.foo from a separate file, as it is very long, but still be able to access A's method foo. 这样做的动机是从一个单独的文件中导入新的b.foo,因为它很长,但是仍然能够访问A的方法foo。

You can't use super outside of a class. 您不能在课程外使用super。 Sorry, that's just how the language is. 抱歉,这就是这种语言。 You could replace super with Object.getPrototypeOf(B.prototype) . 您可以将Super替换为Object.getPrototypeOf(B.prototype) But I'd think hard about splitting a class across several files in the first place. 但是我首先要考虑将一个类拆分为几个文件。

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

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