用一张图来表示新的原型链:
封装一个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; }; // 创建xiaoming: var xiaoming = new PrimaryStudent({ name: ‘小明‘, grade: 2 }); xiaoming.name; // ‘小明‘ xiaoming.grade; // 2 // 验证原型: xiaoming.__proto__ === PrimaryStudent.prototype; // true xiaoming.__proto__.__proto__ === Student.prototype; // true // 验证继承关系: xiaoming instanceof PrimaryStudent; // true xiaoming instanceof Student; // true
原型继承 - 廖雪峰的官方网站 (选自 @廖雪峰)
原文地址:https://www.cnblogs.com/minjh/p/9304127.html
时间: 2024-11-11 07:26:23