javascript继承笔记

//原型(prototype):原型是一个对象,其他对象可以通过它实现属性继承

/*笔记:
* 1.类式继承:通过原型链继承的方式
* 2.原型式继承:对类式继承的封装
* 3.寄生式继承:对原型继承的二次封装,并且在第二次封装过程中对继承的对象进行扩展
* 4.构造函数式继承:通过构造函数继承的方式
* 5.寄生组合式继承:寄生式继承融合构造函数式继承的优点去除缺点的方式
* 6.组合式继承(类式继承+构造函数式继承 两者优点相加)
*/

//原型式继承
function inheritobject(o){
//声明一个过渡函数对象
function F(){
}
//过渡原型对象继承父对象
F.prototype=o;
//返回过渡对象的一个实列,该实例的原型继承了父对象
return new F();
}

var book={
name:"jsbook",
alikeBook:['css book',"html book"],
};

//寄生式继承(对原型继承的第二次封装,并且在第二次封装过程中对继承的对象进行了扩展)
//声明基对象
function createBook(obj){
//通过原型继承方式创建新对象
var o = new inheritobject(obj);
//扩展新对象
o.getName=function(){
console.log(this.name);
}
//返回扩展后的对象
return o;
}

/*
*寄生式继承 继承原型
* 传递参数subclass 子类
* 传递参数superclass 父类
* */
function inheritPrototype(subclass,superclass){
//复制一份父类的原型副本保存在变量中
var p=inheritobject(superclass.prototype);
//修正因为重写子类原型导致子类的constructor属性被修改
p.constructor=subclass;
//设置子类原型
subclass.prototype=p;
}

//定义父类
function superclass(name){
this.name = name;
this.colors=["red","blue","green"];
}

//定义父类原型方法
superclass.prototype.getName=function(){
console.log(this.name);
}

//定义子类
function subclass(name,time){
//构造函数式继承
superclass.call(this,name);
//子类新增属性
this.time=time;
}

//寄生式继承父类原型
inheritPrototype(subclass,superclass);

//子类新增原型方法
subclass.prototype.getTime = function(){
console.log(this.time);
}


//单继承 extend 属性复制
var extend=function(target,source){
//遍历源对象中的属性
for(var property in source){
//将源对象中的属性复制到目标对象中
target[property]=source[property];
}
return target;
}

//多继承 属性复制 可以绑定到原生对象object上
Object.prototype.mix=function(){
var i=0,//从第一个参数起为被继承的对象
len=arguments.length,//arguments相当于多个传递参数的集合,非常类似数组
//target=arguments[0];//第一个传入参数为目标对象
arg; //缓存参数对象
//遍历被继承的对象
for(; i<len;i++){
//缓存当前对象
arg=arguments[i];
for(var property in arg){
//将被继承对象中的属性复制到目标对象中
this[property]=arg[property];
}
}

}


//测试单继承
var b1={
name:'javascript 设计模式',
alike:['css','html','javascript']
}

var b2={
color:'blue'
}
extend(b2,b1);
console.log("单继承测试:"+b2.name+"-"+b2.alike+"-"+b2.color);




/*寄生组合式继承测试 begin*/
console.log("寄生组合式继承测试");
var instance1=new subclass("js book",2014);
var instance2=new subclass("css book",2013);

instance1.colors.push("black");
console.log(instance1.colors);
console.log(instance2.colors);

instance1.getName();
instance1.getTime();

instance2.getName();
instance2.getTime();


/*寄生组合式继承测试 end*/

/*寄生式继承测试 begin*/
console.log("寄生式继承测试");
var newBook=createBook(book);
newBook.name="ajax book";
newBook.alikeBook.push("xml book");

var otherBook=createBook(book);
otherBook.name="flash book";
otherBook.alikeBook.push("as book");

console.log(newBook.name);
console.log(newBook.alikeBook);

newBook.getName();//对对象进行了二次封装,并进行了扩展

console.log(otherBook.name);
console.log(otherBook.alikeBook);
otherBook.getName();
/*寄生式继承测试 end*/

/*json对象 测试*/
console.log(book.name+":"+book.alikeBook);

//测试多继承
otherBook.mix(b1,b2);
console.log(otherBook);

posted on 2016-10-19 11:28  惊涛随笔  阅读(284)  评论(0编辑  收藏  举报

导航