1. var x = 1
  2. var obj = {
  3. x:2,
  4. y:function(){
  5. console.log(this.x)
  6. }
  7. }
  8. setTimeout(obj.y,1000)

谁调用它,this就指向谁。上面例子是 setTimeout 函数调用了 obj.y 方法,而setTimeout 属于 window。

  1. var num = 0
  2. function Obj(){
  3. this.num = 1
  4. this.getNum = function(){
  5. console.log(this.num)
  6. }
  7. this.getNumLater = function(){
  8. setTimeout(function(){
  9. console.log(this.num)
  10. },1000)
  11. }
  12. }
  13. var obj = new Obj
  14. obj.getNum() //obj.num 1
  15. obj.getNumLater() //window.num 0

会出现什么问题

为什么要用 var that = this

文章链接

https://www.jianshu.com/p/3e482748369d?from=groupmessage

https://set.sh/post/180206-keyword-this