目录
JS 面向对象之原型继承
我们知道 Java
是面向对象编程,但其实 JavaScript
也是可以面向对象编程的。
今天介绍一下 JS
基于原型方式的继承。
首先,我们需要定义一个 Student
父类和子类 PrimaryStudent
。
// 定义Student类
function Student(props) {
this.name = props.name || 'Unn amed';
this.age = props.age || 18;
}
// 定义Student子类PrimaryStudent
function PrimaryStudent(props) {
// 改变Student的this指向(继承Student属性)
Student.call(this, props);
this.grade = props.grade || 1;
}
在子类 PrimaryStudent
中使用了 Student.call(this, props)
来改变父类的 this
指向,这样当我们创建子类对象的时候能拥有父类的属性,对 call
函数不了解的可以参考 MDN文档。
接下来我们定义父类和子类的方法。
// 定义Student类的hello方法
Student.prototype.hello = function () {
return 'Hello, ' + this.name + '!';
}
// 定义PrimaryStudent类的方法getGrade:
PrimaryStudent.prototype.getGrade = function () {
return this.grade;
};
将方法绑定在对象原型上可以达到所有对象共用一个方法,从而减小内存的目的。
接下来子类需要继承父类的方法。
// 原型继承链封装函数
function inherits(Child, Parent) {
var F = function () { };
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
// 原型继承链(继承Student方法):
inherits(PrimaryStudent, Student);
这里我们使用空函数 F
来连接子类和父类的原型对象。
到此为止,基于原型的继承就做好了,我们来验证一下继承是否成功。
// 父对象
let parent = new Student({ name: '父', age: '28' })
// 子对象
let child = new PrimaryStudent({ grade: 5 })
我们打开浏览器开发者模式(F12)进入 console
控制台输入 child
就能看到 child
对象的全部信息。
可以看到,子类继承了父类的属性 name
和 age
,由于没有赋值所以取的默认值,同样子类也继承了父类的 hello
方法。
END