一只叫花花的小小鸟

导航

继承的三种方式

//对象冒充方式继承(支持多继承) 
function ClassA(sColor) {
this.color = sColor;
this.sayColor = function () {
console.log(this.color);
};
}
var a = new ClassA("yellow");
function ClassB() {
ClassA.call(this,"blue");
this.ll = "hh";
this.say = function(){
console.log(this.ll);
}
}
var b = new ClassB();
var c = new ClassB();

console.log(b.sayColor === c.sayColor);//false这说明每一个对象都保存了一份sayColor函数的代码体(体现函数 逻辑的数据)
//的副本,显然是一种浪费


//原型方式继承(不支持多继承)
function ClassA() { }
ClassA.prototype.color = "blue";
ClassA.prototype.sayColor = function () {
alert(this.color);
};
function ClassB() { }
ClassB.prototype = new ClassA();
ClassB.prototype.name = "";
ClassB.prototype.sayName = function () {
alert(this.name);
};
var a= new ClassA();
var b= new ClassB();
var c = new ClassB();
console.log(b.sayColor === c.sayColor);//true共享同一份方法
console.log(b.sayColor === a.sayColor);//true
console.log(b.sayName === c.sayName);//true
console.log(b.color === c.color);//true


//混合方式(创建类的最好方式是用构造函数定义属性,用原型定义方法) //用对象冒充继承构造函数的属性,用原型链继承 prototype 对象的方法
function ClassA(sColor) {
this.color = sColor;
}
ClassA.prototype.sayColor = function () {
alert(this.color);
};
function ClassB(sColor, sName) {
ClassA.call(this, sColor);
this.name = sName;
}
ClassB.prototype = new ClassA();
ClassB.prototype.sayName = function () {
alert(this.name);
};
var b = new ClassB("black","kk");
var c = new ClassB("red","ll");

posted on 2017-07-05 11:01  一只叫花花的小小鸟  阅读(157)  评论(0编辑  收藏  举报