一:继承
1.原型链继承
function Box(){
this.name='WANG';
}
Box.prototype.name='LIU';
function Desk(){
this.age = 100;
}
Desk.prototype = new Box();//原型继承Box
var desk = new Desk();
alert(desk.name);//WANG
alert(desk instanceof Object);//true
alert(desk instanceof Desk);//true
alert(desk instanceof Box);//true
2.借用构造函数继承(对象冒充继承)
function Box(name ,age ){
this.name =name;
this.age=age;
this.family =['g','j','d','m']
}
Box.prototype .family = '家庭'
Box.prototype .run = function(){
return this.name + this.age+"ing"
}
function Desk(name.age){
Box.call(this,name,age)//对象冒充,只继承构造不继承原型
}
alert(desk.name);
alert(desk.family);//只输出构造中的值
alert(desk.run());//无法继承原型中的方法函数
3. 组合继承 (1、2结合)
4.原型式继承
function Obj(o){//临时中转函数
function F(){
F.prototype=o;
return new F();//构建对象F,返回F,通过F类似原型继承
}
}
var box={//字面量的声明方式
name:'wang',
age:100,
family:['w','m','l']
};
var box1 = obj(box);
alert(box1.name);//wang
alert(box1.family);
box1.family.push('n');
alert(box1.family);//wmln
var box2 = obj(box);
alert(box2.family);//wmln
5.寄生继承(原型式和工厂模式的结合)
//临时函数
function Obj(o){
function F(){
F.prototype=o;
return new F();//构建对象F,返回F,通过F类似原型继承
}
}
//寄生函数
function create(o){
var f =obj(o);
f.run= function(){
return this.name+'方法';
}
return f;
}
var box={//字面量的声明方式
name:'wang',
age:100,
family:['w','m','l']
};
var box1 = create(box);
alert(box1.name);//wang
<pre name="code" class="javascript">alert(box1.run);//
6.寄生组合继承
//临时函数
function Obj(o){
function F(){
F.prototype=o;
return new F();//构建对象F,返回F,通过F类似原型继承
}
}
//寄生函数
function create(box,desk){
var f = obj(box.prototype);
f.constructor = desk;//调整指针指向
desk.prototype = f;
return f;
}
function Box(name,age){
this.name=name;
this.age= age;
}
Box.prototype.run=function(){
return this.name + this.age +'ing'
}
function Desk(name,age){
Box.call(this,name,age);
}
create(Box,Desk);
var desk = new Desk('wang',100);
alert (desk.run());
alert(desk.constructor);