实现组合继承

/**

  • Person
  • @param {String} name
    */
    function Person(name) {
    this.name = name;
    }
    Person.prototype.sayHello = function() {
    console.log('Hi! My name is ' + this.name + '.');
    }

// TODOS: 改写 Student 类,接收 name 和 grade 属性,并使其继承 Person, 创建实例既有 name 实例属性,又有 sayHello 原型方法。
function Student(name,grade) {
this.grade = grade;
Person.call(this,name);
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
Student.prototype.sayGrade = function() {
console.log('I am Grade ' + this.grade + '.');
}

// 可以正确运行下面代码:
var student = new Student('Cover', 4);
console.log(student.name); // 'Cover'
student.sayHello(); // 'Hi! My name is Cover.'
student.sayGrade(); // 'I am Grade 4.'
student.hasOwnProperty('name'); // true

你可能感兴趣的:(实现组合继承)