您好,欢迎访问一九零五行业门户网

关于子类的prototype=父类的prototype问题

//--- wrong ---/*dog.prototype=animal.prototype;//引用类型赋值,赋的是引用(即内存地址)  引用同一个内存地址 指向同一个对象,可通过任一引用修改该prototype对象 console.log(dog.prototype.constructor); //animal dog.prototype.constructor=dog; //回复prototype对象的constructor的默认值 指向构造函数 dog.prototype.goodat=function(){     alert('i am good at protecting'); }; var animala=new animal('red','pig'); console.log(animala.color + ' '+ animala.name); //red pig animala.sayhi(); // hi, i am a pig animala.goodat();// i am good at protecting   //创建dog.prototype.goodat方法时,其实修改的是animal.protoype对象,子类的原型对象和父类的原型对象为同一对象,子类的原型对象无法独自扩展,扩展属性或方法时,其实修改的是父类的原型对象,所以必须用new 方式创建对象实例,赋值给子类的原型对象(子类的原型对象又是父类的实例对象,这样当子类的实例在它自身和子类的原型对象都找不到方法时,子类的原型对象会向父类的原型对象查找(因为子类的原型对象是父类的实例),这样就形成了原型链)*///--- right ,but not perfect---/*dog.prototype=new animal(); //dog.prototype对象除了有指向animal.prototype对象的引用,还多了个属性 type='animal'; console.log('----------------'); console.log(dog.prototype.constructor); //animal dog.prototype.constructor=dog;//恢复dog.prototype.constructor的默认值  var doga=new dog('black','buddy'); doga.sayhi();// i am a buddy dog.prototype.goodat=function(){     alert('i am good at protecting'); } doga.goodat(); // i am  good at protecting alert(doga.type); //animal,  dog.prototype.type var animala=new animal('green','kitty'); animala.sayhi(); // i am kitty alert(animala.goodat); // undefined*///---- right perfect ----var f=function(){} //一个function对象f.prototype=animal.prototype;  //指向同一个对象 同内存地址dog.prototype=new f(); // 建立原型链 dog的实例对象在自身找不到对应属性,会在prototype对象中找,还是找不到则到f.prototype所指向的地址(即animal.prototype对象)找 (因为dog.prototype是f类的实例对象)
以上就是关于子类的prototype=父类的prototype问题的详细内容。
其它类似信息

推荐信息