admin管理员组文章数量:1435859
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 {
...
}
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 {
...
}
Share
Improve this question
asked May 28, 2017 at 11:01
CodeArtistCodeArtist
5,7148 gold badges45 silver badges66 bronze badges
1
- 1 Looks like you already did? – Bergi Commented May 28, 2017 at 11:21
1 Answer
Reset to default 8Since 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.
本文标签: javascriptCan i replace utilinherits with es639s extend keywordStack Overflow
版权声明:本文标题:javascript - Can i replace util.inherits with es6's extend keyword? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745657647a2668805.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论