Skip to content

Instantly share code, notes, and snippets.

@kwoktung
Created March 1, 2020 05:59
Show Gist options
  • Save kwoktung/c44159dcec8623bf66d3748b00cd7b44 to your computer and use it in GitHub Desktop.
Save kwoktung/c44159dcec8623bf66d3748b00cd7b44 to your computer and use it in GitHub Desktop.
inherits
function inherits(Child, Parent) {
let F = function(){}
// F only inherits Parent method, not instance property
F.prototype = Parent.prototype
Child.prototype = new F()
Child.prototype.constructor = Child;
}
// Usage
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 must write before PrimaryStudent.prototype, otherwise will be rewrited
inherits(PrimaryStudent, Student);
PrimaryStudent.prototype.getGrade = function () {
return this.grade;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment