欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

5分鐘理解JavaScript中this用法分享

 更新時間:2013年11月09日 15:15:41   作者:  
這篇文章介紹了5分鐘理解JavaScript中this用法,有需要的朋友可以參考一下

前言
關(guān)于JavaScript中this的用法網(wǎng)絡(luò)中已經(jīng)有較多比較詳盡的介紹,可以參考本文的參考學(xué)習(xí)資料和網(wǎng)絡(luò)。本文結(jié)合網(wǎng)絡(luò)收集整理,嘗試以一種簡易的方式闡述JavaScript中this的用法,希望對大家關(guān)于JavaScript中this用法的快速理解有所幫助。
正文
1. this用法實(shí)例

復(fù)制代碼 代碼如下:

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

2. this用法簡易理解
this指向哪里:
this運(yùn)行的環(huán)境(the context object),或者簡單理解為:this所在函數(shù)被調(diào)用時的當(dāng)前作用域。
一段實(shí)例代碼立刻明白:
復(fù)制代碼 代碼如下:

var fun = function() {
    console.log(this);
}
fun();// console: window,fun 的執(zhí)行context為window,即this所在函數(shù)(fun())被調(diào)用時的當(dāng)前作用域?yàn)閣indow。
new fun();//console: fun,fun 的執(zhí)行context為fun對象內(nèi),即this所在函數(shù)(fun())被調(diào)用時的當(dāng)前作用域?yàn)閒un對象內(nèi)。

3. this用法的一個特殊情況
(1)情況:
復(fù)制代碼 代碼如下:

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

點(diǎn)擊這個button之后,你會發(fā)現(xiàn)按鈕的value值沒有改變。
原因:在本代碼運(yùn)行的情況下this指向的是window對象。
復(fù)制代碼 代碼如下:

<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>

點(diǎn)擊這個button之后,程序可正常執(zhí)行。
(2)原因解釋:
復(fù)制代碼 代碼如下:

<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>

得到的輸出是:
復(fù)制代碼 代碼如下:

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


復(fù)制代碼 代碼如下:

<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>

得到的輸出是:
復(fù)制代碼 代碼如下:

function onclick() {
    demo();
}

相關(guān)文章

最新評論