这篇文章主要为大家介绍了js面试题继承的方法及优缺点解答,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
目录
说一说js继承的方法和优缺点?
一、原型链继承
二、借用构造函数(经典继承)
三、组合继承
四、原型式继承
五、寄生式继承
六、寄生组合式继承
说一说js继承的方法和优缺点?
要点: 原型链继承、借用构造函数继承、组合继承、原型式继承、寄生式继承、寄生组合式继承、ES6 Class
答:
一、原型链继承
缺点:
- 1.引用类型的属性被所有实例共享
- 2.在创建 Child 的实例时,不能向 Parent 传参
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//原型链继承 function Parent() {
this .parentPrototype = "parent prototype" //验证这种继承方法的确定,如果父类示例中存在一个引用类型的属性,将会被所有子类共享 this .parentObj = {
info: "我是 parent 引用属性parentObj中的 info" } } function Children() {
} //将Children的原型对象指定为Parent的示例,通过原型链,将Parent中的属性赋值给Children示例 Children.prototype = new Parent(); const a = new Children(); console.log(a.parentPrototype); // parent prototype //缺点 const b = new Children(); //在a示例中改动继承的引用属性 a.parentObj.info = "我是a示例中 引用属性parentObj中的 info" //b与a示例共享引用属性 console.log(b.parentObj.info); // 我是a示例中 引用属性parentObj中的 info |
二、借用构造函数(经典继承)
优点:
- 1.避免了引用类型的属性被所有实例共享
- 2.可以在 Child 中向 Parent 传参
缺点: