我最近在学习 Node.js。util.inherits
我对Node.js中的函数有疑问。我可以extends
在咖啡脚本中使用来替换它吗?如果不是,它们之间有什么区别?
问问题
1487 次
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
之间的继承关系。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
(您可以通过将其编译回 JavaScript来检查它是否是一个忠实的复制品。)
这是正在发生的事情:
- 直接找到的所有键
parent
都设置在 上child
。 - 创建了一个新的原型构造函数
ctor
,将其实例的constructor
属性设置为子级,并将其prototype
设置为父级。 - 子类的
prototype
设置为ctor
.ctor
'sconstructor
将被设置为child
,而ctor
's 原型本身是parent
. - 子类的
__super__
属性设置为parent
'sprototype
,供 CoffeeScript 的super
关键字使用。
node的文档描述util.inherits
如下:
将原型方法从一个构造函数继承到另一个构造函数。构造函数的原型将被设置为从 superConstructor 创建的新对象。
作为一个额外的便利, superConstructor 可以通过 constructor.super_ 属性来访问。
util.inherits
总之,如果您使用的是 CoffeeScript 的类,则不需要使用;只需使用 CS 为您提供的工具,您就可以获得super
关键字等奖励。
于 2012-05-21T04:04:38.663 回答