2012-07-16 61 views
0

的CoffeeScript代码:为什么一个类不是它的父类的“instanceof”?

class Animal 
    constructor: (@name) -> 

    move: (meters) -> 
    alert @name + " moved #{meters}m." 

class Snake extends Animal 
    move: -> 
    alert "Slithering..." 
    super 5 

alert Snake instanceof Animal 

这里是a link

我真的认为这个结果是正确的。 我的原因是这样的__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; 
}; 

child.prototype.prototype是父母。

有人能告诉我为什么吗? 我下面知道是真是假:

alert new Snake('a') instanceof Animal 

回答

6

SnakeAnimal一个子类:

class Snake extends Animal 

这意味着,Snake(一个 “类”)实际上是Function,不Animal一个实例。一个Snake对象,另一方面,将是Animal一个实例:

alert Snake instanceof Function  # true 
alert (new Snake) instanceof Animal # true 

如果你试图得到一个Snake实例中移动:

(new Snake('Pancakes')).move() 

你会看到正确的方法叫做。

演示:http://jsfiddle.net/ambiguous/3NmCZ/1/

相关问题