Created
March 1, 2020 05:59
-
-
Save kwoktung/c44159dcec8623bf66d3748b00cd7b44 to your computer and use it in GitHub Desktop.
inherits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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