function inheritPrototype(subType, superType){
var prototype = object(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
}SuperType.prototype.sayName = function(){
alert(this.name);
};function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}inheritPrototype(SubType, SuperType);SubType.prototype.sayAge = function(){
alert(this.age);
};
这题是javascript高级程序设计第2版、面向对象的最后一题,我照抄运行出错、
然后不解的是第二行object(superType.prototype);  //这句语法没见过

解决方案 »

  1.   

    你打错了吧??
    var prototype = object(superType.prototype);
    应该是
    var prototype = Object(superType.prototype);
    才对吧
      

  2.   

    恩,小写改大写的不报错,但没运行结果,可能是书的印刷出错.
    但这样的语法似乎没见过,Object(superType.prototype);起什么作用.我用alert打印了一下结果为Object object
    按我的理解是Object();相当于function Object(){};如果把superType.prototype做为参数的话应该是function Object(){
       function superType.prototype(){
          SuperType.sayName = function(){
             alert(this.name);
          }
       }
    };
      

  3.   

    借这个机会,我也学习一下。理论一向不扎实的说。烦请哪位大侠对有错的,或形容错了的指教一下。谢谢
    function inheritPrototype(subType, superType){
        var prototype = Object(superType.prototype);
        prototype.constructor = subType;//给superType增加了一个constructor属性:subType。这就使得其继承了SubType
        subType.prototype = prototype;//使得subType也继承了superType
    }function SuperType(name){
        this.name = name;
        this.colors = ["red", "blue", "green"];
    }SuperType.prototype.sayName = function(){
        alert(this.name);
    };function SubType(name, age) {
        SuperType.call(this, name);//call:这里相当于构造了SuperType,如果这里不构造。则一切通过构造SubType去访问SuperType的name,colors都会变成undefined
        this.age = age;
    }inheritPrototype(SubType, SuperType);SubType.prototype.sayAge = function(){
        alert(this.age);
    };
    var _A=new SuperType('张三');
    _A.sayName();//张三
    _A.age=99;
    _A.sayAge();//99
    alert(_A.colors);//red,blue,green
    var _B=new _A.constructor('李四',12);
    _B.sayName();//李四  :删除SubType中的SuperType.call(this, name);undefined,因为并没有构造SuperType(name)
    _B.sayAge();//12
    alert(_B.colors);//red,blue,green:删除SubType中的SuperType.call(this, name);undefinedvar _C=new SubType("王五",13);
    _C.sayName();//王五:删除SubType中的SuperType.call(this, name);undefined,因为并没有构造SuperType(name)
    _C.sayAge();//13
    alert(_C.colors);//red,blue,green:删除SubType中的SuperType.call(this, name);undefined,因为并没有构造SuperType(name)
    alert(_C.colors[0]);//red :删除SubType中的SuperType.call(this, name);将报错,因为colors未定义