一.原型链继承
子类prototype指向父类实例的prototype
function Person() {
this.isPerson = true;
}
Person.prototype.sayHello = function() {
console.log('Hello!');
}
function Student(grade){
this.grade = grade;
}
Student.prototype = new Person();
Student.prototype.sayGrade = function(){
console.log("I am Grade "+this.grade);
}
但该方法有几个问题:
1. constructor指向问题。Student的prototype其实是Person的,constructor指向的也是Person。
2.属性共享问题。如果Person实例上有引用值属性,那么不同的Student实例都是用的这个引用值,会有数据污染问题
3.参数。只能用父类的参数
二:借用构造函数继承
借用父类构造函数,可以传递参数
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(){