js多态实现,并且newObj()函数的传参,继承以最后的对象的属性和方法进行覆盖
(function(){
//newObj// 可传入构造函数或者json对象,
function forObj(o1){
function for_(object1,object2){
for(var j in object2){object1[j]=object2[j];}
}
var opt=Object.prototype.toString.call(o1);
var obj0={};
if(opt=='[object Function]'){
for_(obj0,new o1());
}else if(opt=='[object Object]'){
for_(obj0,o1);
}
if(o1.prototype){
var obj1=o1.prototype;
for_(obj1,obj0);
return obj1;
}else{
return obj0;
}
}
function newObj(){
var json={};
var a=arguments;
for(var i=0;i<a.length;i++){
var obj=forObj(a[i]);
for(var j in obj){
json[j]=obj[j];
}
}
return json;
}
function objects(){
this.color='black';
}
objects.prototype={
name:'baidu'
};
function cat2(){
this.age=1;
this.type='cat1';
this.oninit=function(){
console.log(this);
}
}
cat2.prototype= {
age:3,
type:'cat2',
initialize:function(){
this.oninit();
}
};
var cat1={
age:5,
type:'cat3'
};
function dog1(){
this.age=3;
this.type='dog1';
this.oninit=function(){
console.log(this);
}
}
dog1.prototype= {
age:2,
type:'dog2',
initialize:function(){
this.oninit();
}
};
var dog2={
age:1,
type:'dog3'
};
var cat=newObj(objects,cat1,cat2);
var dog=newObj(objects,dog2,dog1);
console.log(JSON.stringify(cat));//{"name":"baidu","color":"black","age":1,"type":"cat1"}
console.log(JSON.stringify(dog));//{"name":"baidu","color":"black","age":3,"type":"dog1"}
cat.initialize();
dog.initialize();
})();
js 多态实现
最新推荐文章于 2024-04-08 09:59:43 发布