核心就是:Person.call(this)
例子:
/**
* 实现 `Student` 构造函数,接受 `name`, `grade` 参数,并且通过借用构造函数继承 `Person`,`Student` 创建的实例满足下列条件:
* 1. 具有 `name` 和 `grade` 实例属性,分别等于输入的参数。
* 2. 具有 `selfIntroduce` 原型方法,调用会输出(`console.log`)字符串 `My name is ${name}. I am Grade ${grade}`, 其中 `name` 和 `grade` 分别对应相应的属性值,
* 3. `student instanceof Student`结果是 `true`, `student instanceof Person` 结果是 `false`。;
*/
/**
* 实现 `Student` 构造函数,接受 `name`, `grade` 参数,并且通过借用构造函数继承 `Person`,`Student` 创建的实例满足下列条件:
* 1. 具有 `name` 和 `grade` 实例属性,分别等于输入的参数。
* 2. 具有 `selfIntroduce` 原型方法,调用会输出(`console.log`)字符串 `My name is ${name}. I am Grade ${grade}`, 其中 `name` 和 `grade` 分别对应相应的属性值,
* 3. `student instanceof Student`结果是 `true`, `student instanceof Person` 结果是 `false`。;
*/
/**
* Person 构造函数
*/
function Person(name,grade) {
this.name = name;
this.grade = grade;
}
Person.prototype.sayHello = function() {
console.log('Hi! I am ' + this.name);
}
// TODOS: 实现 Student
function Student(name,grade){
Person.call(this,name,grade);
// this.grade = grade;
}
Student.prototype.selfIntroduce = function(){
console.log("My name is " + this.name + ". I am Grade " + this.grade);
}
第二种方法:转载自:https://ke.qq.com/classroom/index.html#course_id=233919&term_id=100275850&ch_id=376058&vch_id=46§ion_id=168&task_id=1468045591810495
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log('Hi! I am ' + this.name);
}
function Student(name, grade) {
Person.call(this, name);
this.grade = grade;
}
Student.prototype.selfIntroduce = function() {
console.log('My name is ' + this.name + '. I am Grade ' + this.grade);
}
新增的实现继承的方法:
//继承的方法
function Teacher(name){
this.name = name;
}
Teacher.prototype.sayName = function(){
return "yuanxing";
}
function Student(){
Teacher.call(this,name);
}
Student.prototype = new Teacher(); //实现继承的本质是通过实例父函数,然后赋值给子函数的prototype
var student = new Student("xiao");
console.log(student.name) //xiao
console.log(student.sayName()) //yuanxing
方法二:es6中的extends方法
class Teacher{
constructor(name,age){
this.name = name;
this.age = age;
}
sayName(){
return `父类:${this.name}sd`;
}
}
class Student extends Teacher {
constructor(name,age,color){
super(name,age);
this.color = color;
}
checkPhone(){
return ` ${this.color} `;
}
}
const [age,...rest] = ["xiao","22","red"]; //扩展运算符和结构赋值的结合
console.log(rest); //["22","red"]
let student = new Student("xiao","22","red");
console.log(student.name); //xiao
console.log(student.color); //red
console.log(student.sayName()); //父类:xiaosd
console.log(student.checkPhone()); //red