1. 原型继承
function People(name){
this.name = name;
}
People.prototype.go = function(){
console.log(this.name + '正在走');
}
// 学生
function Student(name){}
Student.prototype.test = function(){
console.log(this.name + '考试');
}
// 原型继承
Student.prototype = new People('继承');
let t1 = new Student('小白');
console.log(t1); // 继承
t1.go()
原型继承的缺点: 所继承的属性值,都和父亲实例对象所传递的值一致,无法重置属性值
2. 冒充继承
function People(name){
this.name = name;
}
People.prototype.go = function(){
console.log(this.name + '正在走');
}
// 冒充继承
function Student(name){
People.call(this,'小米');
}
let d1 = new Student('小白');
console.log(d1);
冒充继承: 通过改变this的指向性,实现属性的继承
缺点: 无法继承挂载在原型对象上的方法
3. 组合继承
function People(name){
this.name = name;
}
People.prototype.go = function(){
console.log(this.name + '正在走');
}
// 组合继承
function Student(name){
People.call(this,name);
}
Student.prototype = new People();
let d2 = new Student('小红');
console.log(d2)
d2.go()
原型链的查找规则图