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

相关推荐
浪客川15 分钟前
【百例RUST - 010】字符串
开发语言·后端·rust
赵侃侃爱分享1 小时前
学完Python第一次写程序写了这个简单的计算器
开发语言·python
whuhewei1 小时前
为什么客户端不存在跨域问题
前端·安全
断眉的派大星1 小时前
# Python 魔术方法(魔法方法)超详细讲解
开发语言·python
2501_933329551 小时前
技术深度拆解:Infoseek舆情处置系统的全链路架构与核心实现
开发语言·人工智能·自然语言处理·架构
妮妮喔妮1 小时前
supabase的webhook报错
开发语言·前端·javascript
我的xiaodoujiao1 小时前
API 接口自动化测试详细图文教程学习系列11--Requests模块3--测试练习
开发语言·python·学习·测试工具·pytest
xiaoye-duck2 小时前
【C++:C++11】C++11新特性深度解析:从类新功能、Lambda表达式到包装器实战
开发语言·c++·c++11
qq_12084093712 小时前
Three.js 大场景分块加载实战:从全量渲染到可视集调度
开发语言·javascript·数码相机
csbysj20202 小时前
Pandas 常用函数
开发语言