创建对象看看, 复制代码 代码如下: var man = new Man("Andy"); var woman = new Woman("Lily"); console.log(man instanceof Man);//true console.log(woman instanceof Woman);//true console.log(man instanceof Person);//true console.log(woman instanceof Person);//true
这让人不悦:从以上的代码看出man的确是通过Man类new出来的 var man = new Man("Andy"),那么对象实例man的构造器应该指向Man,但为何事与愿违呢? 原因就在于$class中重写了Person的原型:c.prototype = p; 好了,我们把$class稍微改写下,将方法都挂在构造器的原型上(而不是重写构造器的原型),如下: 复制代码 代码如下: function $class(constructor,prototype) { var c = constructor || function(){}; var p = prototype || {}; // c.prototype = p; for(var atr in p) c.prototype[atr] = p[atr]; return c; }