5分鐘理解JavaScript中this用法分享_javascript技巧

來源:互聯網
上載者:User

前言
關於JavaScript中this的用法網路中已經有較多比較詳盡的介紹,可以參考本文的參考學習資料和網路。本文結合網路收集整理,嘗試以一種簡易的方式闡述JavaScript中this的用法,希望對大家關於JavaScript中this用法的快速理解有所協助。
本文
1. this用法執行個體

複製代碼 代碼如下:

window.color = “red”;
var o = { color: “blue” };
function sayColor(){
    alert(this.color);
}
sayColor(); //”red”
o.sayColor = sayColor;
o.sayColor(); //”blue”

2. this用法簡易理解
this指向哪裡:
this啟動並執行環境(the context object),或者簡單理解為:this所在函數被調用時的當前範圍。
一段執行個體代碼立刻明白:
複製代碼 代碼如下:

var fun = function() {
    console.log(this);
}
fun();// console: window,fun 的執行context為window,即this所在函數(fun())被調用時的當前範圍為window。
new fun();//console: fun,fun 的執行context為fun對象內,即this所在函數(fun())被調用時的當前範圍為fun對象內。

3. this用法的一個特殊情況
(1)情況:
複製代碼 代碼如下:

<input type="button" id="aButton" value="demo" onclick="demo()" />
<script type="text/javascript">
function demo() {
    this.value = Math.random();
}
</script>

點擊這個button之後,你會發現按鈕的value值沒有改變。
原因:在本代碼啟動並執行情況下this指向的是window對象。
複製代碼 代碼如下:

<input type="button" id="aButton" value="demo" />
<script type="text/javascript">
var button = document.getElementById("aButton");
function demo() {
    this.value = Math.random();
}
button.onclick= demo;
</script>

點擊這個button之後,程式可正常執行。
(2)原因解釋:
複製代碼 代碼如下:

<input type="button" id="aButton" value="demo" />
<script type="text/javascript">
var button = document.getElementById("aButton");
function demo() {
    this.value = Math.random();
}
button.onclick= demo;
alert(button.onclick);
</script>

得到的輸出是:
複製代碼 代碼如下:

function demo() {
    this.value = Math.random();
}


複製代碼 代碼如下:

<input type="button" id="aButton" value="demo" onclick="demo()" />
<script type="text/javascript">
var button = document.getElementById("aButton");
function demo() {
    this.value = Math.random();
}
alert(button.onclick);
</script>

得到的輸出是:
複製代碼 代碼如下:

function onclick() {
    demo();
}

聯繫我們

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