JS中实现继承的几种方式

昨天看了个视频,跟老师学了一下关于“JS中实现继承的几种方式”的知识,然后写下了笔记,觉得老师讲得很通俗易懂。

function Person(name,age) {
    this.name = name;
    this.age = age;
    this.study = function() {
        console.log('正在学习中...');
    }
}

Person.prototype.sex = 'female';
Person.prototype.show = function() {
    console.log('自我介绍...', this.name + '', this.age + '', this.sex);
}

方式一:对象冒充继承,也称构造继承
核心:使用call,以对象冒充的形式调用父类的构造函数,相当于是复制父类的实例属性给子类
缺点:只能继承父类构造函数中的属性和方法,无法继承原型中的属性和方法

function Student(name,age) {
    Person.call(this,name,age); //此时Person中的this指向的是Student的对象  
}

var stu1 = new Student('Lucy',15);  
console.log(stu1.name, stu1.age); //Lucy,15
stu1.study();   //正在学习中...

//无法继承原型中的属性和方法
console.log(stu1.sex);  //undefined
stu1.show;    //undefined

方式二:原型链继承
核心:使用prototype,将父类的对象左右子类的原型
缺点:创建子类实例时,无法向父类构造函数传参,导致继承的父类属性没有值

function Student(name,age) {

}

Student.prototype = new Person();   //将Student的原型指向Person实例,从而继承Person

var stu1 = new Student('Lucy',15);
console.log(stu1.name, stu1.age, stu1.sex); //undefined,undefined,female
stu1.study();   //正在学习中...
stu1.show();    //自我介绍... undefined,undefined,female

方式三:组合继承(对象冒充+原型链)

function Student(name,age) {
    Person.call(this,name,age);
}

// Student.prototype = new Person();  调用了两次父类构造函数,生成了两份实例(子类实习将子类原型上的那份屏蔽,所以性能差点)
Student.prototype = Person.prototype;  //完美

var stu1 = new Student('Lucy',16);
console.log(stu1.name, stu1.age, stu1.sex); //undefined,undefined,female
stu1.study();   //正在学习中...
stu1.show();    //自我介绍... Lucy,16,female

在此做了下笔记,要是有误的地方请大家多多指点。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值