js-高级技术
高级技术:
1、function Person(name,age,job){
this.name=name;
this.age=age;
this.job=job;
}
var person=new Person("zhng",20,"zzzz");
var person=Person("zhng",20,"zzzz"); ---this指的是window对象
2、在使用大量if条件语句的时候:
function createXHR(){
if(typeOf XMLHttpRequest != "undefined"){
createXHR=function(){
return new XMLHttpRequest();
};
}else if(typeOf ActiveXObject !=undefined){
createXHR=function(){
if(typeOf arguments.callee.activeXString !="string"){
var version=["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],
i,len;
for(i=0,len=versions.length;i<len;i++){
try{
new ActiveXObject(versions[i]);
arguments.callee.activeXString=versions[i];
break;
}catch(ex){
//skip
}
}
}
return new ActiveXObject(arguments.callee.activeXString);
};
}else{
createXHR=function(){
throw new Error("NO XHR object available.");
};
}
return createXHR();
}
If语句的每个分支都会为createXHR变量赋值,有效覆盖了原有的函数。
3、函数绑定
var handler={
message:"event handler",
handlerClick:function(event){
alert(this.message);
}
};
var btn=document.getElementById("my-btn");
EventUtil.addHandler(btn,"click",function(event){
handler.handlerClick(event);
})
EventUtil.addHandler(btn,"click",bind(handler.handlerClick,handler));
EventUtil.addHandler(btn,"click",handler.handlerClick.bind(handler));
4、防篡改的对象:
- 不可扩展对象:
var person={name:"zhang"};
//不能再给对象添加属性以及方法
object.preventExtensions(person);
person.age=29;
alert(person.age); //undefined
- 密封的对象:
var person={name:"zhang"};
//不能再给对象删除属性以及方法
object.seal(person);
person.age=29;
alert(person.age); //undefined
delete person.name;
alert(person.name); //zhang
- 冻结的对象
var person={name:"zhang"};
//既不可扩展也密封
object.freeze(person);
person.age=29;
alert(person.age); //undefined
delete person.name;
alert(person.name); //zhang
person.name="hui";
alert(person.name);//zhang
5、拖放:为了元素能够拖放,必须是绝对定位
var DragDrop=function(){
var dragging=null;
diffX=0;
diffY=0;
function handleEvent(event){
//获取事件和目标
event=EventUtil.getEvent(event);
var target=EventUtil.getTarget(event);
//确定事件类型
switch(event.type){
case "mousedown":
if(target.className.indexOf("draggable")>-1){
dragging=target;
diffX=event.clientX-target.offsetLeft;
diffY=event.clientY-target.offsetTop;
}break;
case "mousemove":
if(dragging!=null){
//指定位置
dragging.style.left=(event.clientX-diffX)+"px";
dragging.style.top=(event.clientY-diffY)+"px";
}break;
case "mouseup":
dragging=null;
break;
}
};
return {
enable:function(){
EventUtil.addHandler(document,"mousedown",handleEvent);
EventUtil.addHandler(document,"mousemove",handleEvent);
EventUtil.addHandler(document,"mouseup",handleEvent);
},
disable:function(){
EventUtil.addHandler(document,"mousedown",handleEvent);
EventUtil.addHandler(document,"mousemove",handleEvent);
EventUtil.addHandler(document,"mouseup",handleEvent);
}
}
}();