Javascript中this指向的四种绑定规则

this绑定的四种规则

默认绑定

全局调用函数

  • 在非严格模式下,全局调用函数,此时的this指向window
  • 当函数独立调用时,this指向window
console.log(this === window); //true
//全局调用函数
funtion test(){
	console.log(this === window);比较此时的this和window 的关系
}
test();//true

在这里插入图片描述

  • 在严格模式下 use strict,全局调用函数,此时的this指向undefined
    'use strict'; //启用严格模式
    console.log(this === window); //true
    //全局调用函数
    function test() {
        console.log(this);//打印this
    }
    test();//undefined

在这里插入图片描述


隐式绑定

作为对象的方法调用

  • 当函数作为一个对象的属性即方法时,例如obj.test(),这种调用方式是,函数内部的this指向该调用对象
  • 可以归纳为谁调用指向谁
var obj = {
        test: function () {
            console.log(this);//打印this
            console.log(this === obj);//比较this和obj的关系
        }
    }
    obj.test();//调用函数

在这里插入图片描述


立即执行函数

  • 在非严格模式下的立即执行函数this指向window
  • 当函数内部嵌套一个立即执行函数时,立即执行函数的this指向window
  • 严格模式下和立即执行函数的this指向undefined

我把两种写立即函数的方式都写在同一个函数里面,推荐写第二种方式写立即执行函数。

var obj = {
      test: function () {
          console.log("测试!!");
          /*第一种立即执行函数
          function fun() {
              console.log(this);//打印this
              console.log(this === window);//比较this和window的关系
          }
          fun();//true
          */
          /*第二种立即执行函数*/
          (function fun() {
              console.log(this);//打印this
              console.log(this === window);//比较this和window的关系
          })();
      }
  }
  obj.test();//调用函数

在这里插入图片描述


闭包函数

  • 在非严格模式下,当函数闭包产生的独立调用,this指向window
  • 在严格模式下this指向undefined
var obj = {
    test: function () {
        console.log("测试!!");
        function fun() {
            console.log(this);//打印this
            console.log(this === window);//比较this和window的关系
        }
        return fun;//返回一个函数
    }
}
obj.test()();//等同于fun();所以是独立调用

在这里插入图片描述


隐式丢失

  • 当函数方法进行赋值操作,会有个隐式丢失的现象,这种情况也是独立调用,this指向window
  function fun1(){
       console.log(this);//打印this
       console.log(this===window);//比较this与window的关系
   }
   var obj = {
       fun2: fun1
   };
   //隐式丢失
   var test = obj.fun2;//obj.fun2等同于fun1
   test();//window

在这里插入图片描述


函数作为参数

  • 当函数方法作为参数时,编译过程中,实参被赋值为形参;方法在内部也是独立调用,this指向window
        function fun1() {
            console.log(this);//window
        }

        function test(fun) {
            fun();
        }

        var obj = {
            fun1: fun1
        };
        //编译过程中,实参被赋值为形参;(值的拷贝,浅拷贝的过程)
        test(obj.fun1);//window

在这里插入图片描述


显示绑定

call , apply , bind

  • 通过call , apply , bind 强制绑定this指向对象
  function fun() {
      console.log(this);//obj
  }
  var obj = {
      a: 2,
      fun: fun
  };

  obj.fun();
  var test = obj.fun;
  test.call(obj)//this指向obj
  test.apply(obj)//this指向obj
  test.bind(obj)()//this指向obj

在这里插入图片描述


new绑定

  • 当使用new来使用一个函数,函数就会变成构造函数,产生出一个新的实例对象,返回的this指向实例对象
 function Person(){
      this.name = "1"
      return this
  }

  var test = new Person();
  console.log(test);

在这里插入图片描述


this绑定的四种优先级

  • new > 显式 > 隐式 > 默认
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>