1.基础模式
var web2101=[{
name:'',
age:20,
gender:'men',
tel:xxxxxx,
address:'',
专业:xxxxx
},{
name:'',
age:20,
gender:'men',
tel:xxxxxx,
address:'',
专业:xxxxx
},{
name:'',
age:20,
gender:'men',
tel:xxxxxx,
address:'',
专业:xxxxx
},......];
属性名严重重复,显得代码简陋而冗余
凡是代码重复两次及以上的就应考虑封装
2.工厂模式
function creatStudent(name,age,gender){
var obj=new Object();//创建一个新的object对象
//给新object对象传参
obj.say=function(){}
obj.name=name;
obj.age=age;
obj.gender=gender;
//把参数传给调用者
return obj;
}
var stu1=creatStudent("lisi",20,'men');//{name:,age:,gender:,say:}
var stu2=creatStudent("tom",30,'women');
优点:简化了基础模式的代码量
缺点:
1.对象不能细分
2.浪费内存(内置函数)
解决2:
将共有函数声明在工厂函数外部,在函数内部将指针指向公有函数
function say(){
alert("say---");
}
function creatStudent(name,age,gender){
var obj=new Object();
obj.say=say;
obj.name=name;
obj.age=age;
obj.gender=gender;
return obj;
}
var stu1=creatStudent("lisi",20,'men');//{name:,age:,gender:,say:}
var stu2=creatStudent("tom",30,'women');
这个方法也有不足,全局声明say()全局都可以调用,不独属于我的“工厂”,不太安全
3.构造函数模式
function Student(name,age,gender){
//this->student:name
this.name=name;
this.age=age;
this.gender=gender;
//不需要return
}
var stu1=new Student('lisi',20,'men');
优点:解决对象细分问题
缺点:公有属性/方法 外置
4.原型模式
function Student(name.age){
this,name=name;
this.age=age;
};
Student.prototype.say=function(){
alert("say---");
}
var stu1=new Student("lisi",20);
var stu2=new Student("tom",30);
stu1.say();
stu2.say();
console.log(stu1.say==stu2.say);//返回true
将所有公有的属性和方法存放在构造函数的原型对象中
所有的实例对象能够调用,以及构造函数的原型对象也能调用
5.继承
子类的原型指向父类的原型
function Rich(name,age){
this.name=name;
this.age=age;
}
Rich.prototype.enjoy=function(){
alert("enjoy---");
}
Rich.prototype.money=['card1','card2','card3'];
var r1=new Rich('terry',20);
function Poor(name,age,gender){
this.name=name;
this.age=age;
this.gender=gender;
}
Poor.prototype=Rich.prototype;
Poor.prototype.work=function(){
alert("work---");
}
Rich.prototype.constructor=Poor;
var p1=new Poor("lisi",20,'men');
子类的原型指向父类的实例,父类的实例指向子类的构造函数(将子类的constructor属性指向子类构造函数)
function Rich(name,age){
this.name=name;
this.age=age;
}
Rich.prototype.enjoy=function(){
alert("enjoy---");
}
Rich.prototype.money=['card1','card2','card3'];
var r1=new Rich('terry',20);
function Poor(name,age,gender){
/*this.name=name;
this.age=age;*/
/*对重复的函数进行封装*/
Rich.call(this,name,age);
this.gender=gender;
}
Poor.prototype=new Rich();
Poor.prototype.constructor=Poor;
Poor.prototype.work=function(){
alert("work---");
}
var p1=new Poor("lisi",20,'men');