JS中this到底指向誰?

來源:互聯網
上載者:User

標籤:情況   str   var   val   function   class   上下   16px   text   

  關於this的指向,是一個令人很頭疼的問題。但是,你運氣好,碰到了我。老夫這兒有本祖傳秘籍,看懂這個,媽媽再也不用擔心你的this指向不對啦!

  歸根結底,this指向就一句話:誰最終調用函數,this指向誰!!!

 

 關於這點,老夫有三言相贈:

 

       ① this指向的,永遠只可能是對象!
       ② this指向誰,永遠不取決於this寫在哪!而是取決於函數在哪調用。
       ③ this指向的對象,我們稱之為函數的上下文context,也叫函數的調用者。


  下面,請看具體情況。

  ① 通過函數名()直接調用:this指向window

 

function func(){            console.log(this);        }                //① 通過函數名()直接調用:this指向window        func(); // this--->window        

 

② 通過對象.函數名()調用的:this指向這個對象

 

function func(){            console.log(this);        }//② 通過對象.函數名()調用的:this指向這個對象            // 狹義對象            var obj = {                name:"obj",                func1 :func            };            obj.func1(); // this--->obj                        // 廣義對象            document.getElementById("div").onclick = function(){                this.style.backgroundColor = "red";            }; // this--->div

 

③ 函數作為數組的一個元素,通過數組下標調用的:this指向這個數組

 

function func(){            console.log(this);        }        //③ 函數作為數組的一個元素,通過數組下標調用的:this指向這個數組        var arr = [func,1,2,3];        arr[0]();  // this--->arr

 

④ 函數作為window內建函數的回呼函數調用:this指向window( setInterval setTimeout 等

 

function func(){            console.log(this);        }        //④ 函數作為window內建函數的回呼函數調用:this指向window        setTimeout(func,1000);// this--->window        //setInterval(func,1000);

 

⑤ 函數作為建構函式,用new關鍵字調用時:this指向新new出的對象

 

function func(){            console.log(this);        }//⑤ 函數作為建構函式,用new關鍵字調用時:this指向新new出的對象        var obj = new func(); //this--->new出的新obj

 

 

 

 

JS中this到底指向誰?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.