What's the difference between .call() and super()? Is super() just an es2015 thing? Or does .call() have more functionality?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With