Javascript百学不厌 - this

最近看了一本书,让自己的野路子走走正规路线

方法调用模式:

  方法:当一个函数被保存为对象的一个属性时,我们称它为一个方法。

var obj = {
      fun1: function() {this} // 这时的 this 指向 obj
    }
    obj.fun1()

函数调用模式:

  

var obj = {
      fun1: function() {this},
      fun2: function() {
        var fun3 = function(){
          this...  // 这时的 this 指向 window
        }
        fun3();
      }
    }
    obj.fun2()

这个时候认为的习惯是指向 obj 。 为了解决这个问题 var _this = this 将obj 的this保存起来就可以了。

var obj = {
      fun1: function() {this},
      fun2: function() {
        var _this = this;  // 这里是方法调用模式 this 指向obj
        var fun3 = function(){
          _this  // 不解释了
        }
        fun3();
      }
    }
    obj.fun2()

ES6 箭头函数中的this

function taskA() {
  this.name = 'hello'

  var fn = function() {
    console.log(this) // 输出 window 因为是 函数调用模式,所以指向window
    console.log(this.name)
  }

  var arrow_fn = () => {
    console.log(this) // 输出 window 因为箭头函数自己没有this,于是向上找到taskA()中的this,而taskA()是函数调用模式,所以它的this 指向window
    console.log(this.name)
  }
  fn()
  arrow_fn()
}
taskA()

我们也可以通过 bind call apply 三个函数来强行指定this, 至于这三种方法就不赘述了