Skip to content

Instantly share code, notes, and snippets.

@VeraZab
Created February 11, 2018 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VeraZab/e86f558742b35c11c171198a51a3ffe0 to your computer and use it in GitHub Desktop.
Save VeraZab/e86f558742b35c11c171198a51a3ffe0 to your computer and use it in GitHub Desktop.
When do we need constructors and super in Es6 classes?
/*
* Each class has a .prototype property that by default contains a constructor
* property that points back at the class itself.
*/
class Example {}
console.warn(Example === Example.prototype.constructor);
/*
* We can use the constructor method when we want to set some defaults on a class.
*/
class Base {
constructor() {
// We use constructor to add a default property 'name' on the Example class.
this.name = "A default name";
}
}
console.warn(new Base().name);
/*
* We need to invoke super() inside of a child class if we want to be able to use 'this'
* inside of it's constructor method.
*/
// Example 1: child has no special properties to set
class Child1 extends Base {
describe() {
// We don't need a constructor, we're not setting any child class specific properties.
// this.name comes from the parent.
console.warn(this.name);
}
}
new Child1().describe();
// Example 2: child wants to set own property without invoking super() in constructor
// this throws a SyntaxError: 'this' is not allowed before super()
class Child2 extends Base {
constructor() {
// super(); // will work!
this.name = "I'm child 2";
}
describe() {
console.warn(this.name);
}
}
new Child2().describe();
// Example 3: we can use 'this' in a child class without a constructor.
class Child3 extends Base {
sayName() {
return "I'm child 3";
}
describe() {
console.warn(this.sayName());
}
}
new Child3().describe();
// All this and more, so well explained here: https://javascript.info/function-prototype
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment