原型链: 当我们访问对象的一个属性和方法时,他会先在对象中寻找,如果有直接使用,如果没有则会去原型对象中寻找,如果找到则直接使用,如果还没有则去原型中寻找,直到找到object对象的原型,object对象的原型没有原型,如果在object原型中依旧没有找到,则返回undefined
原型链继承: 将父类的实例化对象,赋值给子类的原型。
优点: 类似于复制了一个对象,构造函数和原型中所有的数据都可以获取到
缺点:
1.原型类继承自身没有办法传参
2.父类所有的属性方法都可以被子类共享
//父类 被拿过去的
function Parent(name,age){
this.name = name;
this.age = age;
}
Parent.prototype.love = function(){
console.log("小屁孩")
}
let par= new Parent("小明","50")
//子类 谁要用谁就是子类
function Ding(name,sex,age){
//构造函数继承 又叫类式继承
Parent.call(this,name,age)
this.h = "d";
}
Ding.prototype = new Parent();
类式继承无法获取父类的原型链
原型链继承,无法直接给父类传参
组合继承 :类式继承 + 原型链继承。结合了两则的优势,弥补了各自的缺点
let d= new Ding("小明","男","20");
console.log(d.name);
d.love();
//定义一个构造函数
function Parent_One_1(){
this.name = name;
this.age = age;
this.sex = sex;
this.a = "10";
this.hoppy=function(){
console.log("喜欢敲代码")
}
}
Parent.prototype.jida =function(){
console.log("考不好,吊起来打")
}
function Parent_One_2(name,sex,age,score){
Parent_One_1.call(this,name,sex,age)
this.score = score;
}
//这种写法和类式继承,部分重叠,继承了构造函数两次 导致内存加剧
// Parent_One_2.prototype = new Parent_One_1();
//换一种写法 原型链继承 直接继承父类的话,会出现传址的问题
Parent_One_2.prototype = Parent_One_1.prototype
let s1 = new Parent_One_2();
s1.jida();