创建一个飞机的对象 该对象具有以下属性和方法
Plane.prototype.fly = function(){
console.log("fly");
}
function Plane(){
this.name = name || "一般飞机";
this.blood = 100;
}
//创建一个飞机的对象
var plane = new Plane("梦想号");
此时,因为军事实力的提升,我们的需求发生改变,需要生产具有攻击能力的战斗机 所以,我们在创建一个攻击机的构造工厂 因为后来生产的飞机是在已有工厂的前提下生产的,所以采用继承的方式来创造战斗机 此时飞机具有的功能有
function AttackPlane(){
Plane.apply(this, "歼击机-01");
this.rotate = true;
}
继承原型上的方法有很多种,如下(此处使用父类和子类代替飞机的关系)
AttackPlane.prototype = Plane.prototype;
AttackPlane.prototype.attack = function(){
console.log("轰炸中。。。。");
}
function AttackPlane(){
Plane.apply(this, "歼击机-01");
this.rotate = true;
}
var plane1 = new Plane();
控制台看效果
所以采用此种方法继承会导致父类多出不需要的方法
2.将父类的对象new一个实例赋予子类的原型
AttackPlane.prototype = new Plane();
AttackPlane.prototype.attack = function(){
console.log("轰炸中。。。。");
}
function AttackPlane(){
Plane.apply(this, "歼击机-01");
this.rotate = true;
}
var plane1 = new Plane();
采用new Plane的方式会导致子类的原型上会将父类的私有属性继承下来,所以也不合适
let temp = function () { };
temp.prototype = Plane.prototype;
AttackPlane.prototype = temp.prototype;
AttackPlane.prototype.attack = function () {
console.log("轰炸....");
}
AttackPlane.prototype.attack = function () {
console.log("轰炸中。。。。");
}
function AttackPlane() {
Plane.apply(this, "歼击机-01");
this.rotate = true;
}
var plane1 = new Plane();
此种方式也没有避免子类的方法顺着原型链传到父类的身上
4.采用
//这种方法写起来比较复杂,没有兼容性问题
AttackPlan.prototype = Object.create(Plan.prototype, {
constructor:AttackPlan
})
//老版本浏览器会有兼容性问题,有时需要左兼容性处理,采用最多
AttackPlan.prototype = Object.setPrototypeOf(AttackPlan.prototype, Plan.prototype);
//最粗暴的方法,大佬的做法
AttackPlan.prototype.__proto__ = Plan.prototype;
AttackPlane.prototype.attack = function () {
console.log("轰炸....");
}
AttackPlane.prototype.attack = function () {
console.log("轰炸中。。。。");
}
function AttackPlane() {
Plane.apply(this, "歼击机-01");
this.rotate = true;
}
var plane1 = new Plane();
这三种情况下,都能避免子类的的方法污染父类的方法 也不会使父类的私有变量跑到子类的原型上去