JavaScript中的工厂方式

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>

// 这种方式叫做工厂方式  缺点:没有new   函数重复----资源浪费   
function CreatePerson(name,gender){ //构造函数


//原料
var obj = new Object();


//加工
obj.name = name;
obj.gender = gender;


obj.showName=function(){
alert(this.name);
}


obj.showGender=function(){
alert(this.gender);
}


//出厂
return obj;
}


var o  = CreatePerson("张三","女");
o.showName();
o.showQQ();


var oB  = createPerson("历史","男");
oB.showName();
oB.showGender();
</script>
</body>
</html>

版权声明:本文为u013772689原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。