1. 程式人生 > >JavaScript:對“this”的學習

JavaScript:對“this”的學習

前言

更多筆記,請參看IT老兵驛站

有半個多月沒有更新部落格了,這半個多月一直在加班,實在沒有精力更新,現在到了調整期,可以將前一段時間的工作進行一下整理。

之前對JS的this的理解一直有點模糊,這次總結一下,因為在工作中總遇到this的問題,如果一直這麼模模糊糊,將會在以後的工作中帶來麻煩,而對於這種躲不開的麻煩,早解決肯定要比晚解決好。

這篇帖子是針對參考中的w3schools的一篇帖子進行學習、翻譯和理解,但我感覺w3schools這篇帖子層次有點不是太清楚。

正文

this是什麼

例子:

var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
        return this.firstName + " " + this.lastName;
    }
};

這裡的this指代的是什麼呢?

What is “this”?
In a function definition, this refers to the “owner” of the function.
In the example above, this refers to the person object.
The person object “owns” the fullName method.

在函式定義中,this指代函式的“擁有者”,例如上面例子中,this就代表person這個物件。

預設繫結

Default Binding
When used alone, this refers to the Global object.
In a browser the Global object is [object Window]:

預設的繫結,單獨使用時,this就指代全域性物件。個人理解,這一條和上一條不矛盾,this還是指代擁有這個變數或者函式的物件,這個時候是全域性變數擁有這個變數,所以就指向了全域性變數。

In strict mode, this will be undefined, because strict mode does not allow default binding:

但是在嚴格模式下,this將會是undefined,因為嚴格模式不允許預設繫結。

明確繫結

Explicit Function Binding
The call() and apply() methods are predefined JavaScript methods.
They can both be used to call an object method with another object as argument.

明確的函式繫結,call()和apply()是JS預定義的方法,他們可以被用於使用另外一個物件作為引數,呼叫這個物件的方法。

var person1 = {
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var person2 = {
    firstName:"John",
    lastName: "Doe",
}
person1.fullName.call(person2);  // Will return "John Doe"

看上面這個例子,this指向了person2,最終輸出的是person2的屬性。

總結

這樣一梳理,感覺對於this的理解就清晰了。

參考

https://www.w3schools.com/js/js_this.asp