this专题

button.onclick = function(){
  console.log(this)  //button 触发事件的元素
}

button.addEventListener('click', function(){
  console.log(this)  //button 该元素的引用
})

$('ul').on('click', 'li', function(){
  console.log(this)  // 看文档啊!
})

只有看文档才知道啊! MDN
this就是call的第一个参数


再来一个有难度的

function X(){
  return object = {
    name: 'object',
    f1(x){
      x.f2()
    },
    f2(x){
        console.log(this)  //A
    }
  }
}
var options = {
  name: 'options',
  f1(){},
  f2(){
    console.log(this)  //B
  }
}
var x = X()
x.f1(options)  //B

function X(){
  return object = {
    name: 'object',
    f1(x){
      x.f2.call(this)
    },
    f2(x){
        console.log('这是object的f2')
        console.log(this)  //C object/options
    }
  }
}
var options = {
  name: 'options',
  f1(){},
  f2(){
    console.log('这是options的f2')
    console.log(this)  //D object/options
  }
}
var x = X()
x.f1(options)  //D object

function X(){
    return object = {
      name: 'object',
      f1(x){
        this.options = x
        this.f2()  //这是object的f2
    },
        f2(){
          console.log('这是object的f2')
          this.options.f2.call(this) //这是options的f2 name: object
      }
    }
  }
  
  var options = {
    name: 'options',
    f1(){},
    f2(){
      console.log('这是options的f2')
      console.log(this)  
    }
  }
  var x = X()
  x.f1(options)  //这是object的f2  这是options的f2 name: object

你可能感兴趣的:(this专题)