鍍金池/ 問答/HTML/ 關(guān)于js this的問題

關(guān)于js this的問題

function foo(){
  setTimeout(()=>{
    console.log("is:",this.id);//42
  },100)
}
var id = 21;
foo.call({id:42})

js中函數(shù)的this是動態(tài)的,要看運行時是誰調(diào)用的,在這里面
foo內(nèi)部的this指向匿名對象
setTimeout是全局調(diào)用的
箭頭函數(shù)沒有this 指向相鄰的外層 即為setTimeout的this
所以為什么不是21 打印結(jié)果為什么是42???
求大神詳細解釋?

回答
編輯回答
熟稔

.call 傳入得對象就是this setTimeout沒有this 用的是 foo的this foo的this就是foo.call傳入的對象

2018年3月15日 21:41
編輯回答
有你在

兩個知識點:

  1. fn.call 和 fn.apply 可以改變函數(shù) fn 體內(nèi)的 this 值
  2. 箭頭函數(shù)根本沒有自己的 this,導(dǎo)致內(nèi)部的 this 就是外層代碼塊的 this。
function foo(){
  console.log(this)  // call 改變了 this 為 {id:42}
  setTimeout(()=>{
    console.log("is:",this.id);//箭頭函數(shù)不綁定 this,所以 this 是父級作用域的this,也就是上面的{id:42}
  },100)
}
var id = 21;
foo.call({id:42})

具體用法,題主可以再去查查 MDN 和 ES6標(biāo)準入門

2018年3月13日 09:05
編輯回答
有點壞

因為你用了箭頭函數(shù)
可以簡單理解為:箭頭函數(shù)內(nèi)部沒有this,如果內(nèi)部使用了this,它就會把定義時的this作為執(zhí)行環(huán)境的一部分保存起來,在執(zhí)行時會使用保存的this。

如果你把箭頭函數(shù)改成function,結(jié)果就不一樣了

function foo(){
  setTimeout(function(){        // 改成function
    console.log("is:",this.id); // 現(xiàn)在會打印21
  },100)
}
var id = 21;
foo.call({id:42})
2018年7月18日 16:45
編輯回答
朽鹿
<input type="button" value="點擊" id="btn">
<script>
    document.getElementById('btn').onclick = function () {
      /*var _this = this;
      setTimeout(function(){
        // 內(nèi)部的this 默認指向window
        _this.value = '哈哈';
      }, 1000);*/

      // 箭頭函數(shù)中的this, 永遠指向它所在作用域中的this
      // 會捕獲其所在上下文的  this 值,作為自己的 this 值
      setTimeout(() => {
        this.value = '哈哈';
      }, 1000);
    }
  </script>
2017年10月20日 19:16