coffeescript中的'extends'与node.js中的'util.inherits'之间的差异

Zhe*_*hen 14 node.js coffeescript

我最近在学习Node.js. 我对util.inheritsNode.js中的函数有疑问.我可以用extendscoffeescript来代替吗?如果没有,它们之间有什么区别?

Ash*_*she 23

是的,你可以用来extends代替它.

至于差异?让我们先来看看CoffeeScript:

class B extends A
Run Code Online (Sandbox Code Playgroud)

让我们看一下CoffeeScript编译器为这个JavaScript 生成的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);
Run Code Online (Sandbox Code Playgroud)

因此,__extends用于声明B和之间的继承关系A.

让我们__extends在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
Run Code Online (Sandbox Code Playgroud)

(您可以通过将其编译回JavaScript来检查这是一个忠实的复制.)

这是发生了什么:

  1. 直接找到的所有键parent都已打开child.
  2. ctor创建一个新的原型构造函数,其实例的constructor属性设置为子级,并将其prototype设置为父级.
  3. 子类prototype被设置为的实例ctor.ctorconstructor将被设置为childctor的原型本身parent.
  4. 子类的__super__属性设置为parent's prototype,供CoffeeScript的super关键字使用.

node的文档描述util.inherits如下:

将原型方法从一个构造函数继承到另一个构造函数.构造函数的原型将设置为从superConstructor创建的新对象.

作为额外的便利,可以通过constructor.super_属性访问superConstructor.

总之,util.inherits如果你使用CoffeeScript的类,你不需要使用; 只需使用CS为您提供的工具,您就可以获得super关键字等奖励.