推荐用JSON来写工厂方法(Factory Method),本人特别喜欢使用JSON的格式,主要原因是条理清晰,整体感强。
推荐用JSON写工厂方法,很好理解,新建对象,然后返回就行了。可读性非常强,推荐下
下面这个例子是用工厂的方法定义两个”角色”对象
var wordspace=document.getElementById("spotlight");
var Character={
crate:function(name,lv,exsist){ //传了3个值
var newobj={
name:name,
lv:lv,
exsist:exsist||false,
spotlight:function(){
wordspace.innerHTML+='Name: '+this.name+' Level: '+this.lv+' Exsist: '+this.exsist;
},
destroy:function(){
wordspace.innerHTML+='Name: '+this.name+' is Gone!!';
return null;
}
};
return newobj;
}
};
var Character1=Character.crate('Vurtne', '23'); //创件角色对象,可读性比常规工厂方法强
var Character2=Character.crate('DrakeDog', '85', true);
Character1.spotlight();
console.log(Character1);
//断开引用,好让环境自动释放内存
Character1=Character1.destroy();
console.log(Character1);
var Character={
crate:function(name,lv,exsist){ //传了3个值
var newobj={
name:name,
lv:lv,
exsist:exsist||false,
spotlight:function(){
wordspace.innerHTML+='Name: '+this.name+' Level: '+this.lv+' Exsist: '+this.exsist;
},
destroy:function(){
wordspace.innerHTML+='Name: '+this.name+' is Gone!!';
return null;
}
};
return newobj;
}
};
var Character1=Character.crate('Vurtne', '23'); //创件角色对象,可读性比常规工厂方法强
var Character2=Character.crate('DrakeDog', '85', true);
Character1.spotlight();
console.log(Character1);
//断开引用,好让环境自动释放内存
Character1=Character1.destroy();
console.log(Character1);