js中的继承问题

mac2022-06-30  27

1、继承的概念:把别人的拿过来变成自己的,但自己不受影响。 2、js中最基本的继承就是原型继承。 3、原型继承:通过修改子级构造函数的prototype指向父级构造函数的实例对象。      function Animal(name){         this.name=name;         this.favor=['eating','sleeping'];     }     Cat.prototype=new Animal('Kitty');     function Cat(color){         this.color=color;     }     var cat=new Cat('blue');     cat.favor.push('swimming');     var cat1=new Cat('pink');     console.log(cat.name+cat.color+cat.favor);     console.log(cat1.name+cat1.color+cat1.favor);   原型继承的缺点: (1)不能父级构造函数传递参数。在这里我新n创建了一个Cat的实例函数,但是这个函数里面的name仍然是Kitty。 (2)父级构造函数中的引用类型的数据会被自己构造函数实例共享。在cat的favor里面添加了一个swimming,但是cat1也多出了一个swimming  
4、借用构造函数继承 目的:把父级所有额属性继承过来。 function Animal(name){         this.name=name;         this.favor=['eating','sleeping'];     } Animal.prototype.say=function(){         console.log('hello');     }//这个行为没有继承     function Cat(color,name){         Animal.call(this,name)         this.color=color;     }     var cat=new Cat('blue','Tom');     cat.favor.push('swimming');     var cat1=new Cat('pink','Candy');        cat.say()     console.log(cat.name+'==='+cat.color+'==='+cat.favor);     cat1.say()     console.log(cat1.name+'==='+cat1.color+'==='+cat1.favor); 借用构造函数继承方式解决了原型继承的两个缺点,但又有了新的问题,无法继承父级构造函数原型中的成员。  
5、组合继承   function Animal(name){         this.name=name;         this.favor=['eating','sleeping'];     }     Animal.prototype.say=function(){         console.log('hello');     }     function Cat(color,name){         Animal.call(this,name)         this.color=color;     }     Cat.prototype=new Animal();     var cat=new Cat('blue','Tom');     cat.favor.push('swimming');     var cat1=new Cat('pink','Candy');     cat.say()     console.log(cat.name+'==='+cat.color+'==='+cat.favor);     cat1.say()     console.log(cat1.name+'==='+cat1.color+'==='+cat1.favor); 缺点:虽然这种方法解决了上诉所有的问题,单数还有一个小小的缺点。父级构造函数中的属性会有冗余(浪费内存)。

转载于:https://www.cnblogs.com/hughman/p/6822132.html

最新回复(0)