14

我最近在学习 Node.js。util.inherits我对Node.js中的函数有疑问。我可以extends在咖啡脚本中使用来替换它吗?如果不是,它们之间有什么区别?

4

1 回答 1

23

是的,您可以使用extends它来代替它。

至于区别?让我们先来看看 CoffeeScript:

class B extends A

让我们看看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);

所以,用于声明和__extends之间的继承关系。BA

__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

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

这是正在发生的事情:

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

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

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

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

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

于 2012-05-21T04:04:38.663 回答