Skip to content

Commit

Permalink
Answer "What are the differences between ES6 class and ES5 function c…
Browse files Browse the repository at this point in the history
…onstructors?" (yangshun#104)
  • Loading branch information
yangshun authored Mar 24, 2018
1 parent 678e77d commit 9bb0a69
Showing 1 changed file with 48 additions and 1 deletion.
49 changes: 48 additions & 1 deletion questions/javascript-questions.md
Original file line number Diff line number Diff line change
Expand Up @@ -970,7 +970,54 @@ baz = 'qux';

### What are the differences between ES6 class and ES5 function constructors?

TODO
Let's first look at example of each:

```js
// ES5 Function Constructor
function Person(name) {
this.name = name;
}

// ES6 Class
class Person {
constructor(name) {
this.name = name;
}
}
```

For simple constructors, they look pretty similar.

The main difference in the constructor comes when using inheritance. If we want to create a `Student` class that subclasses `Person` and add a `studentId` field, this is what we have to do in addition to the above.

```js
// ES5 Function Constructor
function Student(name, studentId) {
// Call constructor of superclass to initialize superclass-derived members.
Person.call(this, name);

// Initialize subclass's own members.
this.studentId = studentId;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

// ES6 Class
class Student extends Person {
constructor(name, studentId) {
super(name);
this.studentId = studentId;
}
}
```

It's much more verbose to use inheritance in ES5 and the ES6 version is easier to understand and remember.

###### References

* https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance
* https://eli.thegreenplace.net/2013/10/22/classical-inheritance-in-javascript-es5

[[] Back to top](#js-questions)

Expand Down

0 comments on commit 9bb0a69

Please sign in to comment.