首页 > 代码库 > JS object factory and inherit sample
JS object factory and inherit sample
/* * 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);
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 objectEntity
return objectEntity, while Person refer to objectEntity
/* * 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);
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。