【发布时间】:2015-04-05 14:50:25
【问题描述】:
我正在学习 javascript 中的不同继承实现,主要遵循 Stoyan Stefanov 的 Javascript Patterns 书。
现在我正在检查 Coffescript 是如何实现它的。所以给定父母和孩子classes 或构造函数:
class Animal
constructor: (@name) ->
move: (meters) ->
alert @name + " moved #{meters}m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
sam = new Snake "Sammy the Python"
sam.move()
它们被编译为:
var Animal, Horse, Snake, sam,
_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;
},
_hasProp = {}.hasOwnProperty;
Animal = (function() {
function Animal(_name) {
this.name = _name;
}
Animal.prototype.move = function(meters) {
return alert(this.name + (" moved " + meters + "m."));
};
return Animal;
})();
Snake = (function(_super) {
_extends(Snake, _super);
function Snake() {
return Snake.__super__.constructor.apply(this, arguments);
}
Snake.prototype.move = function() {
alert("Slithering...");
return Snake.__super__.move.call(this, 5);
};
return Snake;
})(Animal);
sam = new Snake("Sammy the Python");
sam.move();
据我了解,咖啡脚本中继承的实现是不同模式的组合:
1。经典代理构造函数
在这种情况下,我们还重置constructor pointer 并存储超类引用。 Stefanov 定义的“圣杯”。
使用这种模式,孩子只继承原型的属性。
// the proxy function
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
2。复制属性的继承
使用这种模式,我们只需将一个对象的属性复制到另一个对象中
_hasProp = {}.hasOwnProperty;
for (var key in parent) {
if (_hasProp.call(parent, key)) child[key] = parent[key];
}
3。经典模式 - 租用构造器(或借用构造器)
function Snake() {
return Snake.__super__.constructor.apply(this, arguments);
}
问题:
- 我的假设正确吗? coffescript编译器是用1+2+3的吗?
- 复制继承 似乎使用了浅复制,这意味着它不会检查属性是否为对象/数组并开始递归。即使是艰难的结果似乎也是一个完美的深拷贝(对象/数组是副本,而不是引用)。为什么/如何?
- rent-a-constructor 不是在创建继承的重复吗?复制属性然后再次调用父构造函数?
-
_extends函数也可以在对象之间而不是构造函数之间使用吗?
谢谢
【问题讨论】:
标签: javascript oop inheritance coffeescript