当您在 Coffeescript 中扩展类时,编译器生成的代码将一个 JS 类“扩展”到另一个。我懂了:
var Animal, Dog, _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) {
// This function takes a child class and extends it with all
// attributes that are included in the parent class.
for (var key in parent) {
// Need to check that this property was actually a key of the parent.
// The Coffeescript compiler was defensive here against changes to
// the hasOwnProperty function, but you can probably get by with
// parent.hasOwnProperty(key).
if (__hasProp.call(parent, key))
child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
// Set the default constructor of the child based on the parents.
ctor.prototype = parent.prototype;
child.prototype = new ctor();
// Make it possible to call the __super__ easily.
child.__super__ = parent.prototype;
return child;
};
Animal = (function() {
function Animal() {}
// To add methods to this class, you would do this:
// Animal.prototype.foo = function() {...}
return Animal;
})();
Dog = (function(_super) {
__extends(Dog, _super);
function Dog() {
_ref = Dog.__super__.constructor.apply(this, arguments);
// This is where you would extend the constructor to add
// functionality to the subclass.
return _ref;
}
// To add methods to this subclass, or to override base class
// methods, you would do this:
// Dog.prototype.bar = function() {...}
return Dog;
})(Animal);
通过键入
class Animal
class Dog extends Animal
在http://coffeescript.org/进入编译器,然后评论结果。