this指向问题

    // 普通函数,谁调用就指向谁
    // 箭头函数,定义时的父级指向谁它就指向谁,即继承父级this
    const obj = {
      one: 1,
      fn: function name(params) {
        console.log(this, '普通函数') // obj 调用时是obj.fn() 所以是obj在调用,故指向obj
        var vfn = () => {
          console.log(this, '普通函数内部箭头函数') // obj 定义在普通函数内部,普通函数指向obj,所以继承其this
        }
        vfn()
      },
      fnn: () => {
        // "use strict" // es6转es5 会开启严格模式
        function fnname(params) {
          console.log(this, '箭头函数内部普通函数') // 开启严格模式为undefiend,否则为Windows
        }
        fnname()
        console.log(this, '箭头函数') // 在vue中,指向vue, 如果在Windows下那就是指向Windows
      }
    }
    obj.fn()
    obj.fnn()

对比call 、bind 、 apply(对箭头函数无效)

const obj = {
        names: '这是名字',
        fn: function name(a = '', b = '4') {
          // call apply =>arguments = ['参数','3']  bind => arguments = [['参数','3']]
          console.log(arguments, 'arguments')
          console.log(this.names + a + b)
          console.log('a' + [0, 1, 2]) // 输出a0,1,2 类似bind接收参数的方式
        },
        fnn: (a = '', b = '4') => {
          console.log(this.names + a + b)
        }
      }
      const objB = {
        names: '这是objB的名字'
      }
      obj.fn() // 输出  这是名字  this未改变指向obj

      // 将obj内的this指向改为objB
      // call 接受多个参数,第一个为this的新指向,后续为参数
      obj.fn.call(objB, '传参', '1') // 输出  这是objB的名字传参1

      // apply 接受两个参数,第一个为this的新指向,第二个参数必须为数组
      obj.fn.apply(objB, ['传参', '2']) // 输出  这是objB的名字传参2

      // bind返回的是个函数必须自调用 接受两个参数,第一个为this的新指向,第二个参数必须为数组
      // 接收参数的时候只是使用一个参数,也为数组
      obj.fn.bind(objB, ['传参', '3'])() // 输出  这是objB的名字传参,34
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。