1.原型继承
特点:将父类的私有+公有作为子类的共有
将子类的原型指向父类的实例
给B的prototype属性重新赋值为a这个对象,B的原型就是a这个对象
//原型模式 将公有的属性加到prorotype上
Student.prototype.introduce = function(){
console.log("我叫" + this.name + "我今年" + this.age + ",我来学习js啦");
}
var stu1 = new Student("张三",13);
var stu2 = new Student("李四",13);
stu1.introduce();
stu2.introduce();
console.log(stu1.introduce == stu2.introduce);//true
2.call继承
特点:将父类的私有作为子类的私有
//call继承
//父类
function A(x,y){
this.x = x;
this.y = y;
}
//公有的
A.prototype.getX = function(){
console.log(this.x);
}
A.prototype.getY = function(){
console.log(this.y);
}
//子类
function B(x,y,z){
//增加公有属性
this.z = z;
A.call(this,x,y);
}
var b = new B(100,20,30);
console.log(b);//B {z: 30, x: 100, y: 20}
冒充对象继承
特点:将父类的私有+公有 作为子类的私有
//父类
function A(x,y){
this.x = x;
this.y = y;
}
//公有的
A.prototype.getX = function(){
console.log(this.x);
}
A.prototype.getY = function(){
console.log(this.y);
}
//子类
function B(z,x,y){
//增加私有属性
this.z = z;
//创建A这个类的实例
var a = new A(x,y);
//迭代a这个对象
for(var key in a){
//将迭代的属性和值给到a
this[key] = a[key];
}
}
var b = new B(100,20,30);
console.log(b);//B {z: 100, x: 20, y: 30, getX: ƒ, getY: ƒ}
寄生组合继承
特点:将父类的私有作为子类的私有,将父类的公有作为子类的公有
//寄生组合继承
//父类
function A(x,y){
this.x = x;
this.y = y;
}
//共有的
A.prototype.getX = function(){
console.log(this.x);
}
A.prototype.getY = function(){
console.log(this.y);
}
//子类
function B(z){
//增加私有属性
this.z = z;
A.call(this,10,20);
}
//将子类的原型指向父类的原型
B.prototype = A.prototype;
var b= new B(100);
console.log(b);