参考:Javascript Constructors- Why it should be used- Object Oriented Programming in Javascript
1.首先假设你需要创建一个classmate对象,它需要用name,age,city三个属性:
var classmate1 = {};
classmate1.name = 'Gerg';
classmate1.age = 21;
classmate1.city = 'Shanghai';
2.同学asan说:帮我也创建一个对象呗。好勒
var classmate2 = {};
classmate2.name = 'asan';
classmate2.age = 22;
classmate2.city = 'dadongbei';
3.剩下40个学生一看:来来来,一人创一个呗。好勒
//其实我内心是拒绝的,想想,有什么办法可以不用重复上面的动作40遍?
//bingo----我有个朋友叫函数,请它帮帮忙
function createClassmateObject(name,age,city){
var classmate = {};
classmate.name = name;
classmate.age = age;
classmate.city = city;
return classmate;
}
var classmate3 = createClassmateObject('qin','23','hlj');
4.这个时候班主任一看:这玩意不错,来来来,帮老师们都弄份,不多,一共200个人。
//呵呵,no problem
//每次创建一个对象,返回一个对象也忒烦了,有没有省事点的方法?
//bingo-----构造函数
function createTeacherObject(name,age,city){
this.name = name;
this.age = age;
this.city = city;
}
var teacher1 = createTeacherObject('lalala',35,'gz');
teacher1;
>>>undefined
5.不对呀,怎么返回undefined呀。
//bingo----好像漏了个new
function createTeacherObject(name,age,city){
this.name = name;
this.age = age;
this.city = city;
}
var teacher1 = new createTeacherObject('lalala',35,'gz');
teacher1;
>>>createTeacherObject {name: "lalala", age: 35, city: "gz"}
6.注意,返回的是一个对象喔
JavaScript Constructor functions automatically returns the object after it is populated.
网友评论