关于this

this指向:this 永远指向最后调用它的那个对象
  • 示例1
	var name = 'hello'
    function a() {
      var name = 'world'
      console.log(this.name) // hello
      console.log('inner:' + this)
    }
    a()
    console.log('outer:' + this)
  • 示例2
	var name = 'hello'
    var a = {
      name: 'world',
      fn: function() {
        console.log(this.name) // world
      }
    }
    a.fn()
  • 示例3
	var name = 'hello'
    var a = {
      name: null,
      fn: function() {
        console.log(this.name) // hello
      }
    }
    // 将a对象的fn方法赋值给了变量f,但没有调用
    // 注意:使用不带圆括号的函数名是访问函数指针(函数是对象,函数名是指针),而非调用函数
    var f = a.fn
    f()
  • 示例4
	var name = 'hello'
    function fn() {
      var name = 'world'
      innerFunction() // 第一次调用
      function innerFunction() {
        console.log(this.name) // hello
      }
    }
    fn()
改变this指向
	var a = {
      name: 'cherry',
      func1: function() {
        console.log(this.name)
      },
      func2: function() {
        setTimeout(function() { // 最后调用setTimeout的对象是window
          this.func1()
        }, 1000)
      }
    }
    a.func2() // this.func1 is not a function
  • 方法1:ES6的箭头函数
    箭头函数中没有this绑定,必须通过查找作用域链来决定其值。如果箭头函数被非箭头函数包含,则this绑定的是最近一层非箭头函数的this,否则this为undefined
	var a = {
      name: 'world',
      func1: function() {
        console.log(this.name)
      },
      func2: function() {
        setTimeout(() => {
          this.func1()
        },100)
      }
    }
    a.func2()
  • 方法2:在函数内部使用_this = this
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值