面向对象
面向对象为js高级中较难的部分,分为几种模式,和几种继承方法
1. 组合构造函数+原型模式
//由于原型属性会数据共享 为了解决构造传参和共享问题
// 组合构造函数+原型模式
function Box (name,age){
this.name = name;
this.age = age;
this.family = ['父','母','妹']; //不共享 使用构造函数
};
Box.prototype = {
constructor : Box,
run : function(){
return this.name + this.age + this.family;
} //共享 使用原型模式
};
2.动态原型模式
//组合构造函数+原型模式 不管有没有调用原型中的方法 都会初始化原型中的方法
// 所以 把构造函数和原型封装到一起
// 动态原型模式
function Box(name,age){
this.name = name;
this.age = age;
if(typeof this.run != 'function'){ //仅在第一次调用的时候初始化
Box.prototype.run = function(){
return this.name + this.age + '运行中....';
};
}
}
var box = new Box('ww',18);
alert(box.run());
//不能再使用字面量的方式重写原型
3.寄生构造函数
//寄生构造函数 = 工厂模式+构造函数模式
// 使用情况 假设要创建一个具有额外方法的引用类型
function myString(string){
var str = new String(string);
str.addstring = function(){
return this +',被添加了!';
}
return str;
}
var box = new myString('ww');
alert(box.addstring());
4.组合继承
//组合继承 = 原型链 + 借用构造函数
function Box(age){
this.name = ['aa','bb','cc'];
this.age = age;
}
Box.prototype.run = function(){
return this.name + this.age;
};
function Desk(age){
Box.call(this,age); //对象冒充
}
Desk.prototype = new Box(); //原型链继承
var desk = new Desk(100);
alert(desk.run());
//超类型在使用过程中会被调用两次
5.原型式继承
// 原型式继承 借助原型并基于已有的对象创建新对象
function obj(o){ //传递一个字面量函数
function F(){} //创建一个构造函数
F.prototype = o; //把字面量函数赋值给构造函数的原型
return new F(); //最终返回实例化的构造函数
}
var box = { //字面量对象
name : 'ww',
arr : ['aa','bb','cc']
};
var box1 = obj(box); //传递
alert(box1.name);
box1.name = 'ww';
alert(box1.name);
alert(box1.arr);
box1.push('dd');
alert(box1.arr);
var box2 = obj(box); //传递
alert(box2.name);
alert(box2.arr); //引用类型
6.寄生组合式继承
// 寄生组合式继承
// 寄生式继承 用来封装创建对象的过程
function obj(o){
function F(){}
F.prototype = o;
return new F();
}
function create(box,desk){
var f = obj(box.prototype);
f.constructor = desk;
desk.prototype = f;
}
function Box(name){
this.arr = ['aa','bb','cc'];
this.name = name;
}
Box.prototype.run = function(){
return this.name;
}
function Desk(name,age){
Box.call(this,age);
this.age = age;
}
create(Box,Desk);
var desk = new Desk('ww',18);
desk.arr.push('dd');
alert(desk.arr);
alert(desk.run());
var desk2 = new Desk('www',20);
alert(desk2.arr);
alert(desk2.run());
浙公网安备 33010602011771号