1.定义新的构造函数,并在内部用call()调用希望“继承”的构造函数,并绑定this;(注:普通函数需要用new字符调用的即为构造函数,构造函数命名首字母大写)
2.借助中间函数F实现原型链继承
3.继续在新的构造函数的原型上定义新方法。
构造函数:
//原函数 function Student(props){ this.name = props.name ||'Unamed'; } Student.prototype.hello = function(){ alert('Hello'+this.name +'!'); }只要创建了一个新函数,每个函数在创建之后都会获得一个prototype的属性,这个属性指向函数的原型对象(原型对象在定义函数时同时被创建),此原型对象又有一个名为“constructor”的属性,反过来指向函数本身,达到一种循环指向。 所以Student的原型链:
function PrimaryStudent(props){ //调用Student构造函数,绑定this变量 Student.call(this,props); this.grade = props.grade || 1; }关于call()的理解: call的作用相当于通过重新定义this顺带传一些另外需要的参数,调用某个函数 这里call重新定义this调用Student构造函数 参考链接:https://www.cnblogs.com/Shd-Study/archive/2017/03/16/6560808.html
下面开始搭建一个空的函数作为桥接中介:
//空函数 function F(){ } //把F的原型指向Student.proptype F.prototype = Student.prototype; //把PrimaryStudent的原型指向一个新的F对象,F对象的原型正好指向Student.proptype: PrimaryStudent.proptype = new F();对象的constructor属性用于返回创建该对象的函数,也就是我们常说的构造函数。PrimaryStudent的原型发生变化,所以需要手动把PrimaryStudent.proptype.constructor绑定回构造函数PrimaryStudent
//把PrimaryStudent原型的构造函数修复为PrimaryStudent PrimaryStudent.proptype.constructor = PrimaryStudent;继续在PrimaryStudent原型即new F()对象上定义方法:
PrimaryStudent.prototype.getGrade = function(){ return this.grade; }; //创建xiaoming var xiaoming = new PrimaryStudent({ name:'小明', grade:2 }); xiaoming.name; //'小明' xiaoming.grade;//2注:每个对象的proto属性都指向其构造函数的原型
// 验证原型: xiaoming.__proto__ === PrimaryStudent.prototype; // true xiaoming.__proto__.__proto__ === Student.prototype; // true // 验证继承关系: xiaoming instanceof PrimaryStudent; // true xiaoming instanceof Student; // true此时的原型链: 第二步的优化,最好通过封装的inherits函数完成 如果把继承这个动作用一个inherits()函数封装起来,还可以隐藏F的定义,并简化代码:
function inherits(Child, Parent) { var F = function () {}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; }这个inherits()函数可以复用:
function Student(props) { this.name = props.name || 'Unnamed'; } Student.prototype.hello = function () { alert('Hello, ' + this.name + '!'); } function PrimaryStudent(props) { Student.call(this, props); this.grade = props.grade || 1; }实现原型继承链:
inherits(PrimaryStudent, Student);绑定其他方法到PrimaryStudent原型:
PrimaryStudent.prototype.getGrade = function () { return this.grade; };本文为廖雪峰javascript教程学习笔记,如有错误欢迎指正~