你不可不知的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();
}

 

更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/120032525

posted @ 2022-07-18 16:10  忘川信使  阅读(31)  评论(0编辑  收藏  举报