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

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

+4
source share
2 answers
  • super () calls the constructor of the class you extended

    class Foo extends Bar {
      constructor() {
        super();  // calls Bar constructor
      }
     }
    
  • a call is a common function that 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 and automatically passes the correct one this.

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

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

    class Bar {
      log() { 
        console.log("bar-log");
      }
    }
    
    class Foo extends Bar {
      log() {
        super.log();
      }
    }
    
    To call
  • explicitly required

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

, , super call. , , call , super, , , / ( ?) this .

+10

, call super - , :

function Foo() {
   Bar.call(this)
}

class Foo extends Bar {
   constructor() {
      super()
   }
 }

( Bar Foo), super call .

super , call Function.

super . , :

class Bar {
  constructor() {
    //...
  }

  bang() {
    console.log('bang')
  }
}

class Foo extends Bar {
  constructor() {
    super()
    //...
  }

  bang() {
    // call parents method in context of `this`
    super.bang()

    //...
  }
}

call, , Function, this. .

function baz() { console.log(this.bar) }
baz() // -> "undefined"
baz.call({ bar: 'foo' }) // -> "foo"

. , this (global, window). this undefined, baz . call this, .

+3

All Articles