javascript 常见的继承方式

继承是基于"类"的,在没有es6前,一个用来new 的函数就充当了"类"的构造函数,构造函数的prototype上面的属性就等于实例的共享属性。

这篇文章主要记录使用函数实现常见的2种继承方式,理解了这2种继承方式,其他的都不再难理解了

1.原型链继承

复制代码
function Parent(name){
        this.name=name;
}
Parent.prototype.myname=function(){
    console.log("name:"+this.name)
}

function Child(){}
//直接引用
Child.prototype=Parent.prototype;
var child=new Child("小明");
console.log("child",child)
child.myname();//undefined
优点:

直接引用,Parent的prototype属性变化时候也会被变化

弊端:

无法调用"父类"的构造函数,导致无法初始化实例属性

2.构造函数继承

复制代码
function Parent(name){
        this.name=name;
}
 Parent.prototype.myname=function(){
            console.log("name:"+this.name)
}

function Child(...arg){
//直接牵复制
    
   Parent.call(this,...arg)
}
var child=new Child("小明");
console.log("child",child.name)
弊端:

无法继承父类的prototype方法

3.组合模式

结合原型链和构造函数继承的优点

复制代码
function Parent(name){
        this.name=name;
}
 Parent.prototype.myname=function(){
            console.log("name:"+this.name)
}

function Child(...arg){
//直接牵复制
    
   Parent.call(this,...arg)
}
Child.prototype=Parent.prototype;
var child=new Child("小明");
console.log("child",child)
child.myname();

4.es6 的class extends

参考:extends - JavaScript | MDN

相关推荐
4Forsee9 分钟前
【Android】动态操作 Window 的背后机制
android·java·前端
martian6659 分钟前
深入解析C++驱动开发实战:优化高效稳定的驱动应用
开发语言·c++·驱动开发
HappRobot11 分钟前
python类和对象
开发语言·python
用户904438163246013 分钟前
从40亿设备漏洞到AI浏览器:藏在浏览器底层的3个“隐形”原理
前端·javascript·浏览器
小二李17 分钟前
第12章 koa框架重构篇 - Koa框架项目重构
java·前端·重构
鸡吃丸子21 分钟前
React Native入门详解
开发语言·前端·javascript·react native·react.js
盼哥PyAI实验室24 分钟前
Python YAML配置管理:12306项目的灵活配置方案
开发语言·python
漂亮的小碎步丶25 分钟前
【启】Java中高级开发51天闭关冲刺计划(聚焦运营商/ToB领域)
java·开发语言
阿蒙Amon25 分钟前
JavaScript学习笔记:12.类
javascript·笔记·学习
qq_4287232428 分钟前
英语歌10个月之前启蒙磨耳朵
前端