你不可不知的JS面试题(第二期)

1、什么是继承?

子类可以使用父类的所有功能,并且对功能进行扩展。

新增方法
改用方法

(1)、ES6使用extends子类继承父类的方法。

// 父类
class A{
    constructor(name){
        this.name= name;
    }
    getName () {
        return this.name;
    }
};
// 子类继承
class B extends A {
    constructor(name){
       super(name) //  记得用super调用父类的构造方法!
    }
    getName(){
        const name = super.getName();
        return name;
    }
}

var b = new B('2');
console.log(b.getName()); //2

(2)、ES5的继承方法:

// 父类
function P(name) {
this.name = name;
}
// 父类方法
P.prototype.get=function(){
return this.name;
}
// 子类
function C(name){
P.call(this,name);
}
// 封装继承。也就是C.prototype.proto = P.prototype
function I(Pfn,Cfn){
var prototype = Object.create(Pfn.prototype);
prototype.constructor = Cfn;
Cfn.prototype = prototype;
}
// 调用继承方法,并传入参数
I(P,C);

var c = new C(‘maomin’);
console.log(c.get()); // maomin

(3)、ES3实现继承

使用ES3实现继承无非是替代了Object.create(Pfn.prototype),我们先来看下
在这里插入图片描述

大家知道我们封装的I方法是原理是C.prototype.proto = P.prototype。但是我们不推荐这样,因为__proto__是浏览器内置的属性,并不是JS内置的,所以不推荐这样做。我们来封装一个方法来替代Object.create(Pfn.prototype)。

function objectCreate (o) {
function P1() {}
P1.prototype = o;
return new P1();
}

更多请见:http://www.mark-to-win.com/tutorial/50917.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值