为什么要面对对象?
在js中万物皆对象
一、如何构造?
1.基本模式
var students=[{
name:'',
age:'',
address:'',
tel:'',
gender:''
},{
name:'',
age:'',
address:'',
tel:'',
gender:''
},{
name:'',
age:'',
address:'',
tel:'',
gender:''
}];
缺点:包含大量重复代码,所以需要考虑封装
2.工厂模式
function student(name,age,gender){
var obj=new Object();
obj.name=name;
obj.age=age;
obj.gender=gender;
return obj
}
var stu1=student("lisi",20,"men");
优点:大大简化了代码
缺点:1.无法细分对象
2.对于共有属性/方法的存放不够具体
优化方法:将共有方法和属性定义在构造器之外
3.构造函数模式
function Student(name,age,gender){
//this-new{}
this.name=name;
this.age=age;
this,gender=gender;
}
var stu1=new Student("lisi",20,'men');
优点:
解决了对象细分问题
缺点:
对于共有属性和方法的存放,占用内存
4.原型模式:
function Student(name,age,gender){
this.name=name;
this.age=age;
this.gender=gender;
}
Student.prototype.sayHello=function(){
alert("hello");
}
var stu1=new Student();
var stu2=new Student();
将实例对象的所有共有属性和方法存放在原型对象中
缺点:在原型中添加多个属性和方法时较为繁琐
可以使用以下代码优化:
Students.prototype = {
constructor:Students,
eat : function(){
alert("chi");
},
run : function(){
alert("run");
},
sayHello : function(){
alert("hello");
}
}
注意:一定要添加constructor属性为构造函数名,否则原型将被object类型替代出现无法区分构造函数的问题