JS中面向对象中的继承(常用写法)---核心部分
JS中面向对象中的继承(常用写法)—核心部分
1、基本概念
接下来介绍,面向对象中继承的两种常用写法。即混合继承(构造函数+原型)和class继承。推荐class继承
需要用到的知识点,构造函数、原型与原型链。
2、混合继承
2.1构造函数:apply/call实现
function Person(name, age, sex) {//构造函数 this.name = name; this.age = age; this.sex = sex; } Person.prototype.singing = function () {//原型上的方法 console.log('人都唱歌'); } function Student(name, age, sex, pro) { //this:实例对象,即Student类实例 //******继承构造函数里面的属性和方法*******。 //构造函数的继承。arguments:父类函数的参数。 Person.apply(this, arguments); //Person.call(this, name, age, sex); this.pro = pro; }
2.2原型prototype:
(1)原型链继承—最优
//******继承原型下面的方法(原型链继承)*******。 //父类的实例给子类的原型。 //弊端:子类的构造函数被父类覆盖了。 Student.prototype = new Person(); Student.prototype.constructor = Student;//将子类的构造函数恢复
(2)拷贝继承
第一种 for (let i in Person.prototype) { //浅拷贝,for...in...是成立的 Student.prototype[i] = Person.prototype[i]; } 第二种 Object.assign(Student.prototype, Person.prototype);//浅拷贝
这样就实现了继承类里面的构造函数和原型上的方法属性,并且保留了自身的属性方法。
3、class继承
核心关键字:extends、super
super:
class Person { constructor(name, age, sex) {//constructor:构造函数。 this.name = name; this.age = age; this.sex = sex; } showinfo() { return `你的姓名是:${this.name},你今年${this.age}岁,你是${this.sex}的`; } } class Student extends Person { constructor(name, age, sex, pro) { //继承,包括父类属性和方法 这里super当函数使用的。 super(name, age, sex); this.pro = pro; } showinfo() {//重写showinfo方法 console.log(super.showinfo() + `,我的专业是${this.pro}`);//这里super当对象使用,调用父类的方法 } } let s1 = new Student('lisi', 200, '女', 'web开发'); console.log(s1.name);//lisi s1.showinfo();//输出:你的姓名是:lisi,你今年200岁,你是女的,我的专业是web开发
最后
大自然不需要代码,但人类需要。—作者留