第一种情况,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
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
father.prototype = new grandpa();
sun.prototype = new father();
==========================================
father.prototype = new grandpa();
sun.prototype = new father();
光看代码我觉得没有讨论的必要
sun.prototype = new father();
father.prototype = new grandpa();
你这种写法就违背了上面的说法,下面这样就可以了。
father.prototype = new grandpa();
sun.prototype = new father();
第一个例子里面少注释了一行代码...sun.prototype = new father();
father.prototype = new grandpa();
//sun.prototype = new father();希望没给读帖人造成误解...
//第一种:
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属性