看书的时候,有这么一句话,还有一个例子这句话着这样的:通过原型链实现继承时,不能使用对象对面量创建原型的方法。因为这样做就会重写原型链。这句话我实在不明白,然后再看例子:function ChaoLei(){
this.ageone = 1;
}

ChaoLei.prototype.getChaoleiValue = function(){
return this.ageone;
};

function ZiLei(){
this.agetwo = 2;
}

//继承了超类
ZiLei.prototype = new ChaoLei();

//添加新方法
ZiLei.prototype={
getZileiValue:function(){
return this.agetwo;
},

//重写超类中的方法
someOtherMether:function(){
return 3;
}
}
var instance =new ZiLei();
alert  (instance.getChaoleiValue()); 代码如上他说最后一行会返回错误,却是错误了,但是我把代码中红色的someOtherMether改为getChaoleiValue,就可以输出正确的结果了。这不就是说明其实也可以用对象字面量创建原型方法吗? 求解释! 谢谢了 还有就是给我说说为什么用对象字面量创建原型方法就会重写原型链。 实在弄不明白 谢谢

解决方案 »

  1.   

    其实理解起来很简单,可以将原型链理解为一个对象,因此既可以给对象添加属性来扩展原型,也可以直接赋一个对象给原型链,就像赋值一样,先前的值肯定会被当前的值覆盖。
    //可以将obj理解为原型链
    var obj = {
        id: 1,
        get: function(){}
    };//通过属性扩展obj,原来的属性还在,可以访问 obj.id
    obj.name = "object";//通过对象赋值,原来的属性被覆盖,不可以访问 obj.id
    obj = {
        name: "object"
    };function Animal(name){
        this.name = name;
    }//用对象字面量创建原型方法
    Animal.prototype = {
        run: function(){
            alert("超类: " + this.name + " run");
        },
        jump:function(){
            alert("超类: " + this.name + " jump");
        }
    };function Cat(age){
        this.age = age;
    }//原型继承
    Cat.prototype = new Animal("cat");//给子类扩展方法,直接在原型链上添加
    Cat.prototype.say = function(){
        alert("子类: " + this.name + " " + this.age);
    };var cat = new Cat(1);
    cat.run(); //此时可以访问超类方法
    cat.say(); //调用子类自己的方法//重写子类原型链
    Cat.prototype = {
        hello: function(){
            alert("子类: hello " + this.name + " " + this.age);
        }
    };var cat2 = new Cat(2);
    cat.run();    //不能访问超类的属性和方法
    cat2.hello(); //调用子类自己的方法
      

  2.   

        ZiLei.prototype = new ChaoLei();//继承       //这不是添加新方法,这是把 zilei函数的prototype属性给重新赋值了
            ZiLei.prototype={
            getZileiValue:function(){
                return this.agetwo;
            }
    }
    //
    ZiLei.protetype.newfunc = function(){}这样是添加
      

  3.   

    前面的都明白了 这个还是不太明白 //重写子类原型链
    Cat.prototype = {
        hello: function(){
            alert("子类: hello " + this.name + " " + this.age);
        }
    };var cat2 = new Cat(2);
    cat.run();    //不能访问超类的属性和方法
    cat2.hello(); //调用子类自己的方法如果Cat.prototype = {
        hello: function(){
            alert("子类: hello " + this.name + " " + this.age);
        }
    };改成了Cat.prototype.hello = function(){
        
            alert("子类: hello " + this.name + " " + this.age);
        }就可以输出正常结果了是不是就是可以证明我开始说的那句我不明的那句话:通过原型链实现继承时,不能使用对象对面量创建原型的方法。因为这样做就会重写原型链?
      

  4.   

    刚才又发现了一个问题 你倒数第二行 是不是应该把cat改为cat2呢 ?