/*
* 创建一个对象
*/
var obj = {
name:"孙悟空",
age:18,
gender:"男",
sayName:function(){
alert(this.name);
}
};
obj.sayName();
var obj2 = {
name:"猪八戒",
age:28,
gender:"男",
sayName:function(){
alert(this.name);
}
};
var obj3 = {
name:"沙和尚",
age:38,
gender:"男",
sayName:function(){
alert(this.name);
}
};
obj2.sayName();
obj3.sayName();
/*
* 使用工厂方法创建对象
* 通过该方法可以大批量的创建对象
*/
function createPerson(name,age,gender){
var obj = new Object();
//向对象中添加属性
obj.name = name;
obj.age = age;
obj.gender = gender;
obj.sayName = function(){
alert(this.name)
}
//将新的对象返回
return obj;
}
var obj2 = createPerson("猪八戒",28,"男");
var obj3 = createPerson("白骨精",18,"女");
var obj4 = createPerson("蜘蛛精",16,"女");
console.log(obj2);
console.log(obj3);
console.log(obj4);
obj2.sayName();
javascript中采用工厂方法创建对象
最新推荐文章于 2024-08-13 16:15:07 发布