skip to Main Content

So I tested this code:

class C1 {}

C1.prototype. f =function(){ return 1 }

class C2 extends C1 {}

C2.prototype. f =function(){ return super.f()+1 }

And it throws a syntax error: ‘super’ keyword unexpected here.

But if I do:

C2.prototype. f =function(){ return Object.getPrototypeOf(this.constructor.prototype).f() + 1 }

It does return a two!

So does anyone know why ‘super’ doesn’t work? I see no reason for it.

Thanks!

2

Answers


  1. super is a keyword meaning it must be accepted by the interpreter and currently only class can use it. You must backup your method or refer to it remotely if you want the same effect:

    class C1 {}
    
    C1.prototype. f =function(){ return 1 }
    
    class C2 extends C1 {}
    
    C2.prototype. f =function(){ return C1.prototype.f.call(this)+1 }
    
    Login or Signup to reply.
  2. Inside class declarations super refers to the class being extended :

    class C1 {
      f() {return 1};
    }
    
    class C2 extends C1 {
      f() { return super.f()+1 }
    }
    
    let result = new C2 ().f()
    console.log( result);

    Outside class declarations however, super, as a keyword, has no meaning and generates an error: the compiler is not going to attempt to guess what super class a coder might have meant when using the keyword.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search