Home > Web Front-end > JS Tutorial > Regarding the prototype of the subclass = the prototype of the parent class

Regarding the prototype of the subclass = the prototype of the parent class

一个新手
Release: 2017-09-14 11:20:47
Original
1337 people have browsed it
//--- 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类的实例对象)
Copy after login

The above is the detailed content of Regarding the prototype of the subclass = the prototype of the parent class. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template