this指向及如何修改this指向?

96 阅读1分钟

1. 在全局作用域中,this 指向window。

2. 在全局作用域中的函数中,this指向undefined。

3  通过对象调用方法,this指向当前对象。通过引用调用方法,this指向undefined。如果是箭头函数就是从自己作用域链的上一层沿用this 

4. 构造函数中的this,指向实例对象。

5. 事件处理函数中的this,this指向当前节点。

6. 内联事件处理函数中,如果是回调函数中的this,并且'use strict';严格模式下, this指向为undefined , 否则为window ;  如果不在函数中,this指向当前节点。

//call改变this
const obj={
            uname:"pink"
        }
        function fn(x,y){
            console.log(this) //obj
            console.log(this.uname)   // pink
            console.log(x+y)     //3
        }
        // 1.立即调用函数
        // 2.改变this指向
        // 3.多用于继承
        fn.call(obj,1,2)
// apply改变this
  const obj = {
        age: 12,
      };
      function fn(x, y) {}
      // 1,立即调用函数
      // 2.改变this指向
      // 3.返回值就是函数的返回值
      // 区别:传递的参数放到数组里面
      fn.apply(obj, [1, 2]);
      // 使用场景:求数组最大值
      const max = Math.max(1, 2, 3, 4);
      console.log(max);
      const Max1 = Math.max.apply(Math, [1, 2, 3, 4]);
      const Min1 = Math.min.apply(null, [1, 2, 3, 4]);
      console.log(Max1);
      console.log(Min1);
      // 展开运算符
      console.log(Math.max(...[1, 2, 3, 4]));
      // 遍历数组求最大值
// bind改变this
        const obj={
            age:12
        }
        function fn(){
            // console.log(11)
            console.log(this)
        }
        fn.bind(obj)()  // 这个时候没有调用fn()
        // fn()
        // 1.bind不会立即调用函数
        // 2.能改变this指向
        // 3.返回值是个函数,但是这个函数里面的this是更改过的obj
        // const fun = fn.bind(obj)
        // console.log(fun)
        // fun()