Posted on 2011-07-29 00:41
xcp 閱讀(621)
評論(0) 編輯 收藏 所屬分類:
JavaScript高級程序設(shè)計(第2版)
1.高級函數(shù)
1.1 作用域安全的構(gòu)造函數(shù)
>例:function Person(name,age,job){
this.name=name;
this.age=age;
this.job=job;
}
var person = new Person("xcp",23,"program er");
alert(person.name);//xcp
alert(window.name);//undefined
但如果我這樣生成對象呢?
var person = Person("xcp",23,"programer");
alert(window.name);/xcp
這是為什么呢?
問題出現(xiàn)在當沒有使用new操作符來調(diào)用構(gòu)造函數(shù)的情況,由于該this對象是在運行時綁定的,所以直接調(diào)用Person(),this會映射到window上
解決辦法呢?
function Person(name,age,job){
if(this instanceof Person){
this.name=name;
this.age = age;
this.job = job;
}else{
return new Person(name,age,job);
}
}
1.2 函數(shù)綁定
函數(shù)綁定要創(chuàng)建一個函數(shù),可以在特定中指定參數(shù)調(diào)用另外一個函數(shù)。該技巧常常和回調(diào)函數(shù)與事件處理程序一起使用,以便在見函數(shù)作為變量傳遞的時候保留代碼執(zhí)行環(huán)境。
例如:var handler ={
message :"Event handled",
handleClick:function(event){
alert(this.message);
}
}
var btn = document.getElementById("sub");
EventUtil.addHandler(btn,"click",bind(handler.handleClick,handler));
2.高級定時器
2.1 setTimeout clearTimeout
2.2 setIntelval clearInterval
3.拖放
3.1 常用寫法
EventUtil.addHander(document,"mousemove",function(event){
var myDiv = document.getElementById("myDiv");
myDiv.style.left = event.clientX+"px";
myDiv..style.top = event.clientY+"px";
})
名稱: ?4C.ESL | .↗Evon
口號: 遇到新問題?先要尋找一個方案乄而不是創(chuàng)造一個方案こ
mail: 聯(lián)系我