JavaScript DOM進階程式設計2.3 this–我要堅持到底!

來源:互聯網
上載者:User

先從一個例子說起

var sound = 'Roar';function myOrneryBeast(){    this.style.color='green';//window 方法被調用時所屬的對象    alert(sound);}// this 的環境可以隨著函數被賦值給不同的對象而改變function initPage(){    var example=ADS.$('example');    //使用事件屬性方法    example.onlick=myOrneryBeast;    //或者使用ADS.addEvent方法    ADS.addEvent(example,'mouseover',myOrneryBeast);}ADS.addEvent(window,'load',initPage);

 通過call()和apply()重新定義執行環境,同樣我們通過一個例子看一下

function doubleCheck(){    this.message='Are you sure you want to leave?';}doubleCheck.prototype.sayGoodbye=function(){    return confirm(this.message)}initPage(){    var clickedLink=new doubleCheck();    var links=document.getElementsByTagName('a');    for (var i = 0;i<links.length ;i++ )    {        ADS.addEvent(links[i],'click',clickedLink.sayGoodbye);    }}//這部分我一開始也沒看懂,不前面的this 又看了一邊,才稍微有點想明白。
//當sayGoodbye方法在<a>這個HTML中執行時,this所引用的就是這個HTML元素,而不是期望的clickedLink對象ADS.addEvent(window,'load',initPage)

解決辦法:用function對象的call() 或者apply()
讓方法thisy引用window對象的情況下可以clickedLink.sayGoodbye.call(window);或者clickedLink.sayGoodbye.apply(window);

對於call而言,每個參數都應該位於對象之後比如:

functionReference.call(object,argument1,argument2,....);

對於apply(),則應該將方法參數作為一個數組放在第二個參數位置上傳遞:

functionReference.apply(object,arguments)//這是call和apply的唯一區別

//下面函數主要是為了給原始函數(有func參數傳遞)建立一個新的環境。之後雖然原始函數仍然接受同樣的參數,但是他卻有了不同的環境//(菜鳥通過實力圖,理解稍微好一點。僅僅是稍微)function bindFunction(obj,func){    return function ()    {        func.apply(obj,arguments);    }}

將此例用在剛剛的doubleCheck()方法中

function doubleCheck(){    this.message='Are you sure you want to leave?';}douleCheck.prototy.sayGoodbye=function(){    return confirm(this.message);}initPage(){    var clickLink=new doubleCheck();    var links=document.getElementsByTagName('a');    for (var i = 0;i<links.length ;i++ )    {        //已經將剛剛的方法加入ADS庫中        ADS.addEvent(links[i],'click',ADS.bindFunction(clickedLink,clickedLink.sayGoodby));    }}

本節就記錄到這兒了,菜鳥接下來還要繼續學習js的關於try{}catch{}的相關只是。

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.