JavaScript中this的一些坑

來源:互聯網
上載者:User

標籤:java   定義   關鍵字   使用   關鍵點   bin   utc   函數的參數   open   

我們經常在回呼函數裡面會遇到一些坑:

var obj = {  name: ‘qiutc‘,  foo: function() {    console.log(this);  },  foo2: function() {    console.log(this);    setTimeout(this.foo, 1000);  }  }obj.foo2();

執行這段代碼我們會發現兩次列印出來的 this 是不一樣的:

第一次是 foo2 中直接列印 this,這裡指向 obj 這個對象,我們毋庸置疑;

但是在 setTimeout 中執行的 this.foo ,卻指向了全域對象,這裡不是把它當作函數的方法使用嗎?這一點經常讓很多初學者疑惑; 其實,setTimeout 也只是一個函數而已,函數必然有可能需要參數,我們把 this.foo 當作一個參數傳給 setTimeout 這個函數,就像它需要一個 fun 參數,在傳入參數的時候,其實做了個這樣的操作 fun = this.foo,看到沒有,這裡我們直接把fun 指向 this.foo 的引用;執行的時候其實是執行了 fun() 所以已經和 obj 無關了,它是被當作普通函數直接調用的,因此 this 指向全域對象。

這個問題是很多非同步回呼函數中普遍會碰到的;

解決

為瞭解決這個問題,我們可以利用 閉包 的特性來處理:

var obj = {  name: ‘qiutc‘,  foo: function() {    console.log(this);  },  foo2: function() {    console.log(this);    var _this = this;    setTimeout(function() {      console.log(this);        console.log(_this);      }, 1000);  }  }obj.foo2();

可以看到直接用 this 仍然是 Window;因為 foo2 中的 this 是指向 obj,我們可以先用一個變數 _this 來儲存,然後在回呼函數中使用 _this,就可以指向當前的這個對象了;

作為一個建構函式使用

在 js 中,為了實作類別,我們需要定義一些建構函式,在調用一個建構函式的時候需要加上 new 這個關鍵字:

function Person(name) {  this.name = name;  console.log(this);  }var p = new Person(‘qiutc‘);

我們可以看到當作建構函式調用時,this 指向了這個建構函式調用時候執行個體化出來的對象;

當然,建構函式其實也是一個函數,如果我們把它當作一個普通函數執行,這個 this 仍然執行全域:

function Person(name) {  this.name = name;  console.log(this);  }var p = Person(‘qiutc‘);

其區別在於,如何調用函數(new)。

箭頭函數

在 ES6 的新規範中,加入了箭頭函數,它和普通函數最不一樣的一點就是 this 的指向了,還記得在上文中(作為對象的方法調用-一些坑-解決)我們使用閉包來解決 this 的指向問題嗎,如果用上了箭頭函數就可以更完美的解決了:

var obj = {  name: ‘qiutc‘,  foo: function() {    console.log(this);  },  foo2: function() {    console.log(this);    setTimeout(() => {      console.log(this);      }, 1000);  }  }obj.foo2();

可以看到,在 setTimeout 執行的函數中,本應該列印出在 Window,但是在這裡 this 卻指向了obj,原因就在於,給 setTimeout 傳入的函數(參數)是一個箭頭函數:

函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。

根據例子我們理解一下這句話: 在 obj.foo2() 執行的時候,當前的 this 指向 obj;在執行setTimeout 時候,我們先是定義了一個匿名的箭頭函數,關鍵點就在這,箭頭函數內的 this 執行定義時所在的對象,就是指向定義這個箭頭函數時範圍內的 this,也就是 obj.foo2 中的this,即 obj;所以在執行箭頭函數的時候,它的 this -> obj.foo2 中的 this -> obj

簡單來說, 箭頭函數中的 this 只和定義它時候的範圍的 this 有關,而與在哪裡以及如何調用它無關,同時它的 this 指向是不可改變的。

call, apply, bind

在 js 中,函數也是對象,同樣也有一些方法,這裡我們介紹三個方法,他們可以更改函數中的this 指向:

  • call
    fun.call(thisArg[, arg1[, arg2[, ...]]])

它會立即執行函數,第一個參數是指定執行函數中 this 的上下文,後面的參數是執行函數需要傳入的參數;

  • apply
    fun.apply(thisArg[, [arg1, arg2, ...]])

它會立即執行函數,第一個參數是指定執行函數中 this 的上下文,第二個參數是一個數組,是傳給執行函數的參數(與 call 的區別);

  • bind
    var foo = fun.bind(thisArg[, arg1[, arg2[, ...]]]);

它不會執行函數,而是返回一個新的函數,這個新的函數被指定了 this 的上下文,後面的參數是執行函數需要傳入的參數;

這三個函數其實大同小異,總的目的就是去指定一個函數的上下文(this),我們以 call 函數為例;

為一個普通函數指定 this
var obj = {  name: ‘qiutc‘  };function foo() {  console.log(this);  }foo.call(obj);

可以看到,在執行 foo.call(obj) 的時候,函數內的 this 指向了 obj 這個對象,成功;

為對象中的方法指定一個 this
var obj = {  name: ‘qiutc‘,  foo: function () {    console.log(this);  }  }var obj2 = {  name: ‘tcqiu222222‘  };obj.foo.call(obj2);

可以看到,執行函數的時候這裡的 this 指向了 obj2,成功;

為建構函式指定 this
function Person(name) {  this.name = name;  console.log(this);  }var obj = {  name: ‘qiutc2222222‘  };var p = new Person.call(obj, ‘qiutc‘);

這裡報了個錯,原因是我們去 new 了 Person.call 函數,而非 Person ,這裡的函數不是一個建構函式;

換成 bind 試試:

function Person(name) {  this.name = name;  console.log(this);  }var obj = {  name: ‘qiutc2222222‘  };var Person2 = Person.bind(obj);var p = new Person2(‘qiutc‘);console.log(obj);

列印出來的是 Person 執行個體化出來的對象,而和 obj 沒有關係,而 obj 也沒有發生變化,說明,我們給 Person 指定 this 上下文並沒有生效;

因此可以得出: 使用 bind 給一個建構函式指定 this,在 new 這個建構函式的時候,bind 函數所指定的 this 並不會生效;

當然 bind 不僅可以指定 this ,還能傳入參數,我們來試試這個操作:

function Person(name) {  this.name = name;  console.log(this);  }var obj = {  name: ‘qiutc2222222‘  };var Person2 = Person.bind(obj, ‘qiutc111111‘);var p = new Person2(‘qiutc‘);

可以看到,雖然指定 this 不起作用,但是傳入參數還是起作用了;

為箭頭函數指定 this

我們來定義一個全域下的箭頭函數,因此這個箭頭函數中的 this 必然會指向全域對象,如果用call 方法改變 this 呢:

var afoo = (a) => {  console.log(a);  console.log(this);  }afoo(1);var obj = {  name: ‘qiutc‘  };afoo.call(obj, 2);

可以看到,這裡的 call 指向 this 的操作並沒有成功,所以可以得出: 箭頭函數中的 this 在定義它的時候已經決定了(執行定義它的範圍中的 this),與如何調用以及在哪裡調用它無關,包括 (call, apply, bind) 等操作都無法改變它的 this。

只要記住箭頭函數大法好,不變的 this

JavaScript中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.