一、JS重載(個數不一樣,類型不一樣)html
//設置單個P標籤的單個樣式 function prop(name,value){ var firstP = document.getElementById("p1"); firstP.style[name] = value; } prop("color","green"); prop("fontSize","38px");
//設置單個P標籤的多個樣式 function myProp(){ var firstP = document.getElementById("p1"); if(arguments.length == 1){ var temp = arguments[0]; for(p in temp){ firstP.style[p] = temp[p]; } }else if(arguments.length == 2){ firstP.style[arguments[0]] = arguments[1]; } } myProp({ color : "green", fontSize : "38px" });
//設置多個相同標籤的多個樣式 function Prop(){ var allP = document.getElementsByTagName("p"); for(var i = 0; i < allP.length; i++){ if(arguments.length == 1){ var temp = arguments[0]; if(allP instanceof Object){ for(p in temp){ allP[i].style[p] = temp[p]; } }else{ return allP[i].style[temp]; } }else if(arguments.length == 2){ allP.style[arguments[0]] = arguments[1]; } } } Prop({ color : "green", fontSize : "38px" });
//設置多個不一樣標籤的多個樣式 //定義一個對象 function MyObj(ele){ var e; this.eles = []; if(ele.indexOf("#") == 0){ e = document.getElementById(ele.replace("#","")); if(e != null) this.eles.push(e); }else{ e = document.getElementsByTagName(ele); if(e != null && e.length > 0){ this.eles = document.getElementsByTagName(ele); } } } //給對象添加一個設置元素樣式的方法 MyObj.prototype.prop = function(){ if(arguments.length !=1 && arguments.length != 2){ return ; } var ele = this.eles; for(var i = 0; i < ele.length; i ++){ if(arguments.length == 1){ if(arguments[0] instanceof Object){ for(p in arguments[0]){ ele[i].style[p] = arguments[0][p]; } }else{ return ele[i].style[arguments[0]]; } }else{ ele[i].style[arguments[0]] = arguments[1]; } } } //建立一個對象 var my$ = function (ele){ return new MyObj(ele); } //調用方法 my$("p").prop("fontSize","30px"); my$("p").prop({backgroundColor : "red", color : "green"});
二、JS繼承this
對象繼承 prototype
//繼承一個父類 var child = {name : "張三"}; var parent = {age : 18}; function myExtends(cObject,pObject){ for(var p in pObject){ cObject[p] = pObject[p]; } return cObject; } var exChild = myExtends(child,parent); console.log(exChild);
//繼承多個父類 var a = {name : "Rose"}; var b = {age : 20}; var c = {sex : "女"}; var d = {tel : 123}; function SuperExtends(){ var child = arguments[0]; for(var i = 1; i < arguments.length; i++){ var parent = arguments[i]; for(p in parent){ child[p] = parent[p]; } } return child; } console.log(SuperExtends(a,b,c,d));