33.js的this是啥

146 阅读1分钟

this是什么

在js中,我们经常会用到this,那么this到底是什么?
this的意思为“这个;当前”,是一个指针型变量,它动态指向当前函数的运行环境。

全局环境下的this

node环境

  • 非严格模式
(function () {
  console.log(this); // global
})(); 
  • 严格模式
(function () {
  'use strict';
  console.log(this); // ndefined
})();

游览器环境

是不是严格模式都是window

    <script>
     'use strict'; 
      console.log(this); // Window
    </script>

函数内的this

普通函数

普通函数的this指向函数的调用者

  • 普通模式下
      function foo() {
        console.log(this); // window
      }
      foo();
  • 严格模式
      function foo() {
        'use strict';
        console.log(this); // undefined
      }
      foo();

箭头函数

箭头函数的this指向当前执行上下文的环境,严格模式下也是如此

  'use strict';
      const foo = () => {
        console.log(this);
      };
      const obj = {
        foo: () => {
          console.log(this);
        }
      };
      foo(); // window
      obj.foo(); // window

对象中的this

对象中普通函数的this指向该对象,dom绑定的事件指向该dom

      const obj = {
        foo: function () {
          console.log(this);
        },
        children: {
          foo: function () {
            console.log(this);
          }
        }
      };
      obj.foo(); // obj
      obj.children.foo(); // obj.children

构造函数中的this

构造函数中的this指向实例

      function Person(name, age) {
       this.name = name;
       this.age = age;
       console.log(this); //Person {name: '刘德华', age: 18}
     }
     const ldh = new Person('刘德华', 18);

改变this指向

箭头函数

箭头函数的this指向执行上下文对象

apply call bind

在函数后调用这三个,可以是this指向改成第一个参数

      const obj = {
       foo: function () {
         console.log(this);
       }
     };
     obj.foo.call(window); // window