Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: What's the difference between .call() and super()?

What's the difference between .call() and super()? Is super() just an es2015 thing? Or does .call() have more functionality?

like image 990
Nick Cordova Avatar asked Jun 26 '16 00:06

Nick Cordova


1 Answers

  • super() calls the constructor of the class you extened

    class Foo extends Bar {
      constructor() {
        super();  // calls Bar's constructor
      }
     }
    
  • call is a generic function you can use with any function

    function a() { console.log(this); };
    function b() { console.log(this); };
    function c() { console.log(this}; };
    
    a.call("hello");
    b.call(123);
    c.call({});
    
  • super knows which class you inherited from and automatically passes the correct this.

    class Foo extends Bar {
      constructor() {
        super();  // calls Bar's constructor
      }
    }
    
  • call requires you to be explicit.

    class Foo extends Bar {
      constructor() {
        Bar.call(this);  // You had explicitly specify 'Bar' 
                         // and explicitly pass 'this'
      }
    }
    
  • super lets you call functions on the parent implicitly

    class Bar {
      log() { 
        console.log("bar-log");
      }
    }
    
    class Foo extends Bar {
      log() {
        super.log();
      }
    }
    
  • call requires you to be explicit

    class Bar {
      log() { 
        console.log("bar-log");
      }
    }
    
    class Foo extends Bar {
      log() {
        Bar.prototype.log.call(this);  // Explicitly reference bar's log function
                                       // and explicitly specify 'this'
      }
    }
    

I think you could argue super offers a subset of the functionality of call. Some might call it syntactic sugar meaning you can use call everywhere you can use super, super is just easier because it implicitly calls stuff from the class you extended/inherited from (technically the next thing up the prototype chain?) and because it implicitly passes this for you.

like image 176
gman Avatar answered Sep 20 '22 10:09

gman