成长(15/2000)——面试题合集12

继承

  • 原型链继承
    缺点:1.一个实例改变了原型的值,其他同样继承该原型的也会变化;
    2.新实例无法向父类构造函数传参。
    3.继承单一
let Parent = function () {
    this.name = ['dq'] //地址,如果是dq是值
}
Parent.prototype.getName =  function () {
    return this.name;
}

function Child () {
    
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

const child = new Child();
const child1 = new Child();
child1.name[0] = "xz"
console.log(child.name,child.getName);
console.log(child1.name,child1.getName);
  • 构造函数继承
    解决了1.原型链继承中被修改的问题;
    2.继承单一的问题,可以call多个;
    3.无法向父类构造函数传参的问题

缺点:1.无法访问父类的原型的方法和属性
2.只继承了父类构造函数的属性,没有继承父类原型的属性。
3、每个新实例都有父类构造函数的副本,臃肿。

let Parent = function () {
    this.name = ['dq']
}
Parent.prototype.getName =  function () {
    return this.name;
}

//在子类的构造函数中,执行父类的构造函数,并且为其绑定子类的this
function Child () {
    Parent.call(this,'xz')
}

const child = new Child();
const child1 = new Child();

child1.name[0] = 'wyb';
console.log(child.name,child.getName);
console.log(child1.name,child1.getName);
// [ 'dq' ] undefined
// [ 'wyb' ] undefined
  • 组合继承
    解决上面无法继承父类原型的问题
    特点:1、可以继承父类原型上的属性,可以传参,可复用。
       2、每个新实例引入的构造函数属性是私有的。
    缺点:每次实例化都会new一次parent实例(耗内存)
let Parent = function () {
    this.name = ['dq']
}
Parent.prototype.getName =  function () {
    return this.name;
}

//在子类的构造函数中,执行父类的构造函数,并且为其绑定子类的this
function Child () {
    Parent.call(this,'xz')
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

const child = new Child();
const child1 = new Child();

child1.name[0] = 'wyb';
console.log(child.name,child.getName);
console.log(child1.name,child1.getName);
// [ 'dq' ] [Function]
// [ 'wyb' ] [Function]
  • 寄生组合式继承
    解决上面的问题
    缺点:
let Parent = function () {
    this.name = ['dq']
}
Parent.prototype.getName =  function () {
    return this.name;
}

//在子类的构造函数中,执行父类的构造函数,并且为其绑定子类的this
function Child () {
    Parent.call(this,'xz')
}

Child.prototype = Parent.prototype;
// Child.prototype = Object.create(Parent.prototype); //对原型的浅拷贝
Child.prototype.constructor = Child;

const child = new Child();
const child1 = new Child();

child1.name[0] = 'wyb';
console.log(child.name,child.getName);
console.log(child1.name,child1.getName);

参考:
1.js继承的6种方式

  1. JS实现继承的几种方式
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,748评论 1 45
  • 1.js当中有哪些数据类型 5个基础:字符串,布尔,数值,null,undefined,1个复杂:Object在e...
    林不羁吖阅读 268评论 0 0
  • 请参看我github中的wiki,不定期更新。https://github.com/ivonzhang/Front...
    zhangivon阅读 7,186评论 2 19
  • <a name='html'>HTML</a> Doctype作用?标准模式与兼容模式各有什么区别? (1)、<...
    clark124阅读 3,567评论 1 19
  • 表情是什么,我认为表情就是表现出来的情绪。表情可以传达很多信息。高兴了当然就笑了,难过就哭了。两者是相互影响密不可...
    Persistenc_6aea阅读 126,098评论 2 7