Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between 'extends' in coffeescript and 'util.inherits' in node.js

I am learning Node.js recently. I have a question about the function util.inherits in Node.js. Can I use extends in coffeescript to replace it? If not, what are the differences between them?

like image 486
Zhe Chen Avatar asked May 21 '12 03:05

Zhe Chen


1 Answers

Yes, you can use extends in place of it.

As for the differences? Let's start with a look at CoffeeScript:

class B extends A

Let's look at the JavaScript the CoffeeScript compiler produces for this JavaScript:

var B,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

B = (function(_super) {

  __extends(B, _super);

  function B() {
    return B.__super__.constructor.apply(this, arguments);
  }

  return B;

})(A);

So, __extends is used to declare the inheritence relationship between B and A.

Let's restate __extends a bit more readably, in CoffeeScript:

coffee__extends = (child, parent) ->
  child[key] = val for own key, val of parent

  ctor = ->
    @constructor = child
    return
  ctor.prototype = parent.prototype

  child.prototype = new ctor
  child.__super__ = parent.prototype

  return child

(You can check that this is a faithful reproduction by compiling it back to JavaScript.)

Here's what's happening:

  1. All the keys found directly on parent are set on child.
  2. A new prototype constructor ctor is created, with its instances' constructor properties set to the child, and its prototype set to the parent.
  3. The child class's prototype is set to an instance of ctor. ctor's constructor will be set to child, and ctor's prototype itself is parent.
  4. The child class's __super__ property is set to parent's prototype, for use by CoffeeScript's super keyword.

node's documentation describes util.inherits as follows:

Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor.

As an additional convenience, superConstructor will be accessible through the constructor.super_ property.

In conclusion, you don't need to use util.inherits if you're using CoffeeScript's classes; just use the tools CS gives you, and you get bonuses like the super keyword.

like image 166
Asherah Avatar answered Oct 08 '22 13:10

Asherah