第一种情况,alert出的是undefined.function grandpa(){
this.name = "grandpa";
}
function father(){
//this.name = "father";
}
function sun(){
}
sun.prototype = new father();
father.prototype = new grandpa(); 
sun.prototype = new father();
//new  grandpa();
var aboy = new  sun();
alert(aboy.name);
第二种情况,交换如下代码的位置,结果alert出 grandpa。father.prototype = new grandpa(); 
sun.prototype = new father();
很明显 第二种情况是想要的结果。请问,原型在指定的时候为什么需要这样的顺序,其中的原理是什么?javascript

解决方案 »

  1.   

    sun.prototype = new father();
    father.prototype = new grandpa(); 
    sun.prototype = new father();
    ==========================================
    father.prototype = new grandpa(); 
    sun.prototype = new father();
    光看代码我觉得没有讨论的必要
      

  2.   

    原型的绑定不能晚于实例创建之前,也就是说原型的绑定要在创建实例之前。
    sun.prototype = new father();
    father.prototype = new grandpa();
    你这种写法就违背了上面的说法,下面这样就可以了。
    father.prototype = new grandpa();
    sun.prototype = new father();
      

  3.   

    竟然不能编辑自己的帖子!
    第一个例子里面少注释了一行代码...sun.prototype = new father();
    father.prototype = new grandpa(); 
    //sun.prototype = new father();希望没给读帖人造成误解...
      

  4.   


    //第一种:
    sun.prototype = new father();//sun.prototype = {},一个空对象
    father.prototype = new grandpa();//father.prototype = {name : "grandpa"}
    var aboy = new  sun();
    //aboy = {};类sun的构造函数中没添加属性,类sun的原型是一个空对象,所以aboy是一个空对象
    //第二种:
    father.prototype = new grandpa();//father.prototype = {name : "grandpa"}
    sun.prototype = new father();
    //sun.prototype = {name : "grandpa"}。任意new 一个father对象都有一个name属性,来自于类father的prototype。
    var aboy = new  sun();//aboy = {};类sun的prototype有一个name属性,所以aboy有一个name属性
      

  5.   

    最有一个注释错了,是//aboy ={name:"grandpa"}