JS this指向

119 阅读1分钟

一、谁调用指向谁

1、直接调用指向window

    function fn() {
      console.log(this)
    }
    fn() // window

2、对象调用指向对象

    const obj = {
      fn: function () {
        console.log(this)
      }
    }
    obj.fn() // obj

二、构造函数this指向实例化对象

    function obj_fn() {
      this.fn = function () {
        console.log(this)
      }
    }
    const xxx = new obj_fn()
    xxx.fn() // xxx

三、箭头函数this指向

  • 指向创建箭头函数时的作用域
    const fn1 = () => {
      console.log(this) // window
    }
    const obj = {
      fn2: () => {
        console.log(this) // window
      },
      fn3: function () {
        return () => {
          console.log(this) // obj
        }
      }
    }
    fn1()
    obj.fn2()
    obj.fn3()()

四、修改this指向

1、call() 使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数

语法:function.call(thisArg, arg1, arg2, ...)

  • thisArg:this指向的目标,不传默认执行全局对象
  • arg...:其他参数
    function Father(name, age) {
      this.name = name
      this.age = age
      this.book = ['数据结构', '计算机网络', '算法']
    }
    function Sun(name, age) {
      // 将Father函数的this指向Sun再调用
      Father.call(this, name, age)
    }
    const sun1 = new Sun('gxm', '20')
    sun1.book.push('javaScript')
    console.log(sun1.book) // ['数据结构', '计算机网络', '算法', 'javaScript']

    const sun2 = new Sun('xz', '22')
    console.log(sun2.book) // ['数据结构', '计算机网络', '算法']

2、apply() 使用一个指定的 this 值和数组或类数组对象来调用一个函数

语法:function.apply(thisArg, argsArray)

  • thisArg:this指向的目标,不传默认执行全局对象
  • argsArray:数组或类数组对象
    function num_arr() {
      this.num = [1, 2, 3]
    }
    function fn(name, age) {
      // 将num_arr函数的this指向fn再调用
      num_arr.call(this)
    }
    const obj = new fn()
    obj.num.push(4)
    console.log(obj.num) // [1,2,3,4]

3、bind() 返回一个函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

    // 给window绑定x属性值为1
    this.x = 1
    const obj = {
      x: 2,
      getX: function () {
        return this.x
      }
    }

    console.log(obj.getX()) // 返回:2;对象调用返回对象的x

    // 获取对象的方法
    const window_getX = obj.getX
    console.log(window_getX()) // 返回:1; 函数在全局作用域中调用返回window的x

    // 创建一个新函数,把 'this' 指向 obj 对象
    const bind_obj_getX = window_getX.bind(obj)
    console.log(bind_obj_getX()) // 2