Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i replace util.inherits with es6's extend keyword?

I am trying to transform some es5 code to es6 and I stumbled upon the following code and I am wondering if I could replace the util.inherits with the extends keyword for classes. I am a bit confused if they do the same thing.

ES5

var EventEmitter = require('events').EventEmitter;
var util = require('util');

function TheEmitter() {
    EventEmitter.call(this);
}
util.inherits(TheEmitter, EventEmitter);

ES6

const EventEmitter = require('events').EventEmitter;

class TheEmitter extends EventEmitter {
   ...
}
like image 691
CodeArtist Avatar asked May 28 '17 11:05

CodeArtist


People also ask

What is util inherits?

The util. inherits() method basically inherits the methods from one construct to another. This prototype will be set to a new object to that from the superConstructor. By doing this, we can mainly add some validations to the top of Object. setPrototypeOf(constructor.

What is the difference between class& prototypes in JavaScript?

Prototypes vs. Classes. The most important difference between class- and prototype-based inheritance is that a class defines a type which can be instantiated at runtime, whereas a prototype is itself an object instance.

Does node JS support inheritance?

By default, each class in Node. js can extend only a single class. That means, to inherit from multiple classes, you'd need to create a hierarchy of classes that extend each other.

Why should we use ES6 classes?

ES6 classes are syntactic sugar for the prototypical class system we use today. They make your code more concise and self-documenting, which is reason enough to use them (in my opinion). will give you something like: var Foo = (function () { function Foo(bar) { this.


1 Answers

Since the class and extends keywords are only syntactic sugar on top of prototypal inheritance, the answer simply is: Yes, you can replace util.inherits by extends and keep the same behavior.

Of course, there are minor things to watch out for, e.g. you need to make sure to call the super constructor in your derived class's constructor, whereas with util.inherits you had to call the constructor function and apply it to this. But effectively, these things are only other syntactic constructs, semantically, they are equivalent.

Then, of course, there are some practical issues, where both options differ from each other. E.g., when defining Foo using the class keyword, you can not call Foo without using the new keyword. Without the class keyword, this is perfectly possible (although not meaningful, so you shouldn't have done this anyway).

So, to cut a long story short: Apart from some strange effects that only happen if you used rare and strange constructs (like calling a constructor function without new), the transition should be seamless.

like image 74
Golo Roden Avatar answered Sep 21 '22 10:09

Golo Roden