您的位置:首页 > 移动开发 > Objective-C

JS object factory and inherit sample

2014-05-16 07:16 846 查看
/*
* Object factory
*/
function objectFactory(jsonObj){
function objectEntity(){

}
if(typeof jsonObj == "object"){
for(var index in jsonObj){
objectEntity.prototype[index] = jsonObj[index];
}
}
return objectEntity;
}

var Person = objectFactory({
pname:'andy',
sex:'man'
});

var person = new Person();
console.info(person+"--"+Person);// [object Object] -- function objectEntity(){}
console.info(person.pname);
console.info(person.sex);
 <span></span>
<span>objectFactory create object per json obj-jsonObj
create function objectEntity will check whether jsonObj is object, and iterate the json object, set attribute value to </span><span>objectEntity</span>
<span>return objectEntity, while Person refer to objectEntity</span>
/*
* inherit
*/
function inherit(obj,prop){
function f(){

}
if(typeof obj=="object"){
for(var index in obj){
f.prototype[index] = obj[index];
}
}else{
f.prototype = obj.prototype;
for(var index in prop){
f.prototype[index] = prop[index];
}
}

return f;
}

var Animal = inherit({
type:'animal',
name:'animal',
jump:'jump'
});

var Dog = inherit(Animal,{
name:'i am a dog',
jump:'dog jumpping'
});

var dog = new Dog;
console.info(dog.type);
console.info(dog.name);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: