1. 程式人生 > 其它 >js中this是什麼?this的5種用法

js中this是什麼?this的5種用法

概述:
1.在方法中,this指的是所有者物件。
2.單獨的情況下,this指的是全域性物件。
3.在函式中,this指的是全域性物件。
4.在函式中,嚴格模式下,this指的是undefined。
5.在事件中,this指的是接收事件的元素。
**

分述:
**

1.方法中的this
在物件方法中,this指的是此方法的“擁有者”。
this代表person物件

 var person = {
            firstName:"Bill",
            lastName:"Gates",
            id:678,
            fullName:function
(){ return this.firstName + " " + this.lastName; } };

2.單獨的this

(1)在單獨使用時,擁有者是全域性物件,this指的是全域性物件
在瀏覽器視窗中,全域性物件是[object Window]:

 var x = this;
 document.getElementById("demo").innerHTML = x;

(2)在嚴格模式中,如果單獨使用,那麼this指的是全域性物件[object Window]:

"use strict";
var x = this
;

3.函式中的this(預設)

在js函式中,函式的擁有者預設繫結this.
因此,在函式中,this指的是全域性物件[object Window]

function myFunction(){
    return this;
    }

4.函式中的this(嚴格模式)

js嚴格模式不允許預設繫結,因此,在函式中使用時,在嚴格模式下,this是未定義的undefined

“use strict”;
function myFunction(){
    return this;
}

5.事件處理程式中的this

this指的是html元素,如下面例子中,this指的是button

<button onclick = "this.style.display='none'">
     點選來刪除我!
</button>