this 指向问题

219 阅读1分钟

一道 this指向问题

var name = "windowsName";
function func1(){
  console.log('windows func1')
}
var a = {
  name: 'test',
  func1: function() {
    console.log('a.func1')
    console.log(this.name)
  },
  func2: function(){
    setTimeout(function(){
      this.func1()
    }, 100)
  }
};
a.func2()    // 输出结果为 windows func1

从输出结果看 setTimeout的对象是window,所以输出结果如上。

在函数内部使用_this = this

var name = "windowsName";
function func1(){
  console.log('windows func1')
}
var a = {
  name: 'test',
  func1: function() {
    console.log('a.func1')
    console.log(this.name)
  },
  func2: function(){
    let _this = this;
    setTimeout(function(){
      _this.func1()
    }, 100)
  }
};
a.func2()    // 输出结果为 a.func1

使用箭头函数

引用MDN一句话箭头函数不会创建自己的`this,它只会从自己的作用域链的上一层继承this

var name = "windowsName";
function func1(){
  console.log('windows func1')
}
var a = {
  name: 'test',
  func1: function() {
    console.log('a.func1')
    console.log(this.name)
  },
  func2: function(){
    setTimeout(() => {
      this.func1()
    }, 100)
  }
};
a.func2()    // 输出结果为 a.func1

使用apply call bind

使用apply

var name = "windowsName";
function func1(){
  console.log('windows func1')
}
var a = {
  name: 'test',
  func1: function() {
    console.log('a.func1')
    console.log(this.name)
  },
  func2: function(){
    setTimeout(() => {
      this.func1()
    }.bind(a), 100)
  }
};
a.func2()    // 输出结果为 a.func1

使用call

var name = "windowsName";
function func1(){
  console.log('windows func1')
}
var a = {
  name: 'test',
  func1: function() {
    console.log('a.func1')
    console.log(this.name)
  },
  func2: function(){
    setTimeout(() => {
      this.func1()
    }.call(a), 100)
  }
};
a.func2()    // 输出结果为 a.func1

使用bind

var name = "windowsName";
function func1(){
  console.log('windows func1')
}
var a = {
  name: 'test',
  func1: function() {
    console.log('a.func1')
    console.log(this.name)
  },
  func2: function(){
    setTimeout(() => {
      this.func1()
    }.bind(a)(), 100)
  }
};
a.func2()    // 输出结果为 a.func1