Coffeescript代码:
class Animal
constructor: (@name) ->
move: (meters) ->
alert @name + " moved #{meters}m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
alert Snake instanceof Animal
Run Code Online (Sandbox Code Playgroud)
这是一个链接.
我真的认为这个结果是真的.我的理由是这个__extends方法在编译的JavaScript中:
__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;
};
Run Code Online (Sandbox Code Playgroud)
child.prototype.prototype 是父母.
有人可以告诉我为什么吗?我知道以下是真的:
alert new Snake('a') instanceof Animal
Run Code Online (Sandbox Code Playgroud)
你Snake是以下的子类Animal:
class Snake extends Animal
Run Code Online (Sandbox Code Playgroud)
这意味着Snake("类")实际上是一个实例Function,而不是Animal.一个Snake对象,另一方面,将是一个实例Animal:
alert Snake instanceof Function # true
alert (new Snake) instanceof Animal # true
Run Code Online (Sandbox Code Playgroud)
如果你试图让一个Snake实例移动:
(new Snake('Pancakes')).move()
Run Code Online (Sandbox Code Playgroud)
你会看到正确的方法被调用.
演示:http://jsfiddle.net/ambiguous/3NmCZ/1/
| 归档时间: |
|
| 查看次数: |
168 次 |
| 最近记录: |