javascript_prototypal inheritance

//javascript_prototype inheritance

//-------------------------------------- Code 1:
'use strict'
function inherits(Child, Parent) {
    var F = function () {};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
}
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;
}

// Implement the prototypal inheritance chain:
inherits(PrimaryStudent, Student);

// Bind other methods to the PrimaryStudent prototype:
PrimaryStudent.prototype.getGrade = function () {
    return this.grade;
};
//--------------------------------------Code 1 explanation:
//1.inherits() method reuse to achieve prototype inheritance

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325345968&siteId=291194637