javascript常用代码段搜集
1.json转字符串
functionjson2str(o){
vararr=[];
varfmt=function(s){
if(typeofs=='object'&&s!=null)returnjson2str(s);
return/^(string|number)$/.test(typeofs)?"'"+s+"'":s;
};
for(variino)arr.push("'"+i+"':"+fmt(o[i]));
return'{'+arr.join(',')+'}';
}
2.时间戳转为Date
functionfromUnixTime(timeStamp){
if(!timeStamp||timeStamp<1000||timeStamp=='')return"";
vartheDate=newDate(parseInt(timeStamp)*1000);
returntheDate;
}
3.Data-format
//作者:meizz
//对Date的扩展,将Date转化为指定格式的String
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q)可以用1-2个占位符,
//年(y)可以用1-4个占位符,毫秒(S)只能用1个占位符(是1-3位的数字)
//例子:
//(newDate()).Format("yyyy-MM-ddhh:mm:ss.S")==>2012-12-0208:12:04.423
//(newDate()).Format("yyyy-M-dh:m:s.S") ==>2012-12-028:12:4.18
Date.prototype.Format=function(fmt){
varo={
"M+":this.getMonth()+1, //月份
"d+":this.getDate(), //日
"h+":this.getHours(), //小时
"m+":this.getMinutes(), //分
"s+":this.getSeconds(), //秒
"q+":Math.floor((this.getMonth()+3)/3),//季度
"S":this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt))
fmt=fmt.replace(RegExp.$1,(this.getFullYear()+"").substr(4-RegExp.$1.length));
for(varkino)
if(newRegExp("("+k+")").test(fmt))
fmt=fmt.replace(RegExp.$1,(RegExp.$1.length==1)?(o[k]):(("00"+o[k]).substr((""+o[k]).length)));
returnfmt;
};
4.日期上增加n天
functionaddDay(number){
returnfromUnixTime(newDate().getTime()/1000+24*60*60*number);
}
5.使用iframe时,父窗体与子窗体之间的相互调用
//父窗体调用子窗体内的函数
window.frames['ifm_id'].valueChange("id_101");
//子窗体调用父窗体的函数
parent.refreshTree("nodeId_202");
6.弹出窗体与返回值
//弹出窗体 varurl="http://www.baidu.com"; win=window.showModalDialog(url,window,"dialogLeft:400;dialogTop:200;dialogWidth:560px;dialogHeight:380px;scroll:yes;menubar:no;toolbar:no;status:no;"); //在弹出窗体中设置返回值 varresult=newArray(); result[0]="id_101"; result[1]="name_202"; window.returnValue=result; window.close();
7.javascript作用域[只有全局作用域和函数作用域,javascript没有块作用域]
//1.全局作用域
varid="globalvariable"; //1.1在函数外部定义的变量
functionshowMsg(){
message="globalmessage";//1.2未定义而直接赋值的变量
// 在第一次使用时被定义为全局变量
}
//2.函数作用域
functiondoCheck(){
vardata="functiondata";//2.1在函数内部定义的变量
}
8.javascript继承机制
//1.对象冒充继承
functionPerson(strName){
//privatefields
varname=strName;
//publicmethods
this.getName=function(){
returnname;
};
}
functionStudent(strName,strSchool){
//定义父类的属性及方法
this.parent=Person;
this.parent(strName);
deletethis.parent; //删除临时变量parent
//定义新属性及方法
//privatefields
varschool=strSchool;
//publicmethods
this.getSchool=function(){
returnschool;
};
}
//2.Funtion对象的call(..)或apply(..)继承
// call和apply的区别在于:
// call 的第二个参数为可变参数;
// apply的第二个参数为Array;
functionAnimal(strName,intAge){
//privatefields
varname=strName;
varage=intAge;
//publicmethods
this.getName=function(){
returnname;
};
this.getAge=function(){
returnage;
};
}
functionCat(strName,intAge,strColor){
//定义父类的属性及方法
Animal.call(this,strName,intAge);
//Animal.apply(this,newArray(strName,intAge));
//定义新属性及方法
//privatefields
varcolor=strColor;
//publicmethods
this.getInfo=function(){
return"name:"+this.getName()+"\n"
+"age:"+this.getAge()+"\n"
+"color:"+color;
};
}
//3.prototype继承
// prototype声明的属性及方法被所有对象共享
// prototype只有在读属性的时候会用到
Function.prototype.extend=function(superClass){
//此处的F是为了避免子类访问父类中的属性this.xxx
functionF(){};
F.prototype=superClass.prototype;
//父类构造函数
this.superConstructor=superClass;
this.superClass=superClass.prototype;
this.prototype=newF();
this.prototype.constructor=this;
};
Function.prototype.mixin=function(props){
for(varpinprops){
this.prototype[p]=props[p];
}
};
functionBox(){}
Box.prototype={
getText:function(){
returnthis.text;
},
setText:function(text){
this.text=text;
}
};
functionCheckBox(){}
CheckBox.extend(Box);
CheckBox.mixin({
isChecked:function(){
returnthis.checked;
},
setChecked:function(checked){
this.checked=checked;
}
});
9.call,apply&bind
//thisArg表示在fun内部时this所指示的对象 //call&apply将立即执行fun并返回结果 varresult=fun.call(thisArg,arg1,...); varresult=fun.apply(thisArg,[argsArray]); //thisArg表示在fun内部时this所指示的对象 //bind返回的是一个匿名函数 vartmpfun=fun.bind(thisArg); varresult=tmpfun(arg1,...);
<scripttype="text/javascript">
/**
*扩展Function的功能
*/
Function.prototype.bind=function(obj){
varmethod=this;
vartmpfun=function(){
returnmethod.apply(obj,arguments);
};
returntmpfun;
}
functionParent(){
this.name="parent";
}
functionChild(){
this.name="child";
this.getName=function(time){
returntime+""+this.name;
};
}
varparent=newParent();
varchild=newChild();
alert(child.getName(1)); //show1child
alert(child.getName.call(parent,2)); //show2parent[call&apply会立即执行]
vartmpfun=child.getName.bind(parent);//bind不会立即执行
alert(tmpfun(3)); //show3parent
</script>
10.js"=="Operator
转换规则
如果一个操作数是Boolean值,则比较之前将其转成数字:false->0,true->1;
如果一个操作数是数字,另一操作数是字符串,则比较之前将字符串转成数字;
如果一个操作数是对象,另一操作数是数字或字符串,则比较之前会将对象转为基本类型,
引擎会先尝试调用valueOf(),如果valueOf()没有override或返回一个对象,
则引擎会尝试调用toString(),如果toString()没有override或返回一个对象,则抛出异常;
如果是两个对象进行比较,则判断它们是否引用同一对象;
如果一个操作数是NaN,==将返回false,!=将返回true;
null和undefined与其它值比较将返回false,
但null==null,undefined==undefined,null==undefined;
参与比较时null和undefined不能转为其它值;