You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
//父类:动物functionAnimal(){this.isLife=truethis.characteristic=['living','eat']}Animal.prototype.earnLiving=function(){console.log('Animal need earn its living.')}//子类:鸟类functionBird(){this.canFly=true}/*原型链继承:通过将子类的原型重写为父类的实例实现继承。*/Bird.prototype=newAnimal()/*继承后,子类就会拥有父类的属性和方法,这也是继承和原型链的目的。*/Bird.prototype.flying=function(){console.log('I am bird, I am flying.')}letsparrow=newBird()/*继承后,子类就会拥有父类的属性和方法,这也是继承/原型链的目的。*/sparrow.earnLiving()console.log('After inherit sparrow.isLife = '+sparrow.isLife)sparrow.flying()/*原型链继承的弊端:公用引用类型问题*/sparrow.characteristic.push('grayFeather')// ["living", "eat", "grayFeather"]leteagle=newBird()/*公用引用类型问题是指,子类的所有实例都会共享原型链上的引用类型属性:eagle也会继承sparrow的grayFeather,这往往不是想要的结果。*/console.log(eagle.characteristic)// ["living", "eat", "grayFeather"]// 只有`引用类型`会被共享, 基础类型(String, Number等)并不会
//父类:动物functionAnimal(type){this.type=typethis.isLife=truethis.characteristic=['living','eat']}//原型链继承:Animal.prototype.earnLiving=function(){console.log('Animal need earn its living.')}//子类:鸟类functionBird(){//借用构造函数继承Animal.call(this,'Bird')this.canFly=true}//原型链继承:Bird.prototype=newAnimal()Bird.prototype.flying=function(){console.log('I am bird, I am flying.')}letsparrow=newBird()sparrow.characteristic.push('grayFeather')console.log(sparrow.characteristic)// ["living", "eat", "grayFeather"]console.log(sparrow.type)//可以在继承时传递参数//继承了父类方法sparrow.flying()leteagle=newBird()/*解决了原型链继承的公用引用类型弊端,sparrow和eagle都有各自独立的引用类型-数组属性。*/console.log(eagle.characteristic)//["living", "eat"]//继承了父类方法eagle.earnLiving()
继承是面向对象语言的一大特性。通过继承,可以让一种类型拥有其他类型的属性和方法。
JavaScript也有自己实现继承的方式,本文将参考《JavaScript高级程序设计》总结并介绍3种常用常见的继承方式。
0.原型链继承:
这种方法通过将子类的原型重写为父类的实例实现继承。
1. 借用构造函数继承
这种方法是通过
借调
父类的构造函数,从而在子类实例的环境下,让子类的实例独立地继承父类的属性和方法,能够避免原型链继承所导致的公用引用类型问题和不能在继承时传递参数的缺点。2. 组合继承
这种方式将原型链继承和借用构造函数继承组合在一起,取长补短,既通过在原型上定义方法实现
函数复用
,又保证每个实例都有自己的属性,避免了公用引用类型
问题。是JavaScript中最常用的一种继承方式。3. 识别实例和原型
原生JavaScript有很多方法可以用来检测原型和实例之间的关系,比如:
Object.prototype.isPrototypeOf({})
Object.getPrototypeOf(anInstance) === Object.prototype
anInstance instanceof anConstructor
4. 特殊情况
The text was updated successfully, but these errors were encountered: