全局执行环境中,浏览器下this指向window,Node.js中指向global;严格模式下全局函数内this为undefined;箭头函数不绑定this,继承外层词法作用域的this值。
this 指向什么在浏览器中,全局作用域下 this 指向 window 对象;Node.js 环境中则指向 global 对象。但要注意:严格模式下全局函数内部的 this 是 undefined,而非 window。
function foo() { console.log(this === window); } // true"use strict"; function foo() { console.log(this); } // undefinedthis,它继承外层函数作用域的 this 值,哪怕在外层是全局环境this 怎么绑定当函数作为对象属性被调用(即 obj.method()),this 指向该对象。这是最常见也最容易理解的绑定方式,但容易在提取方法后丢失上下文。
obj.method() → this 是 obj
const fn = obj.method; fn(); → this 不再是 obj,而是全局对象(非严格)或 undefined(严格)fn.bind(obj)、obj.method.bind(obj)、箭头函数封装、或使用 class 字段语法(method = () => {})this
这三个方法都用于手动指定函数执行时的 this 值,区别只在参数传递形式:
func.call(obj, arg1, arg2):参数逐个传入func.apply(obj, [arg1, arg2]):参数以数组形式传入const bound = func.bind(obj, arg1):返回新函数,this 和部分参数被预设bind 两次不会覆盖第一次绑定 —— 第二次绑定无效,this 仍为第一次指定的对象th
is 为什么不能被改变箭头函数没有自己的 this 绑定,它从定义时所在的词法作用域“捕获”外层的 this 值,并且这个值无法被 call、apply、bind 或作为对象方法调用所修改。
obj.arrowFunc.call(otherObj),this 仍是定义时外层的 this
this 丢失,比如:class Counter { constructor() { this.count = 0; this.timer = setInterval(() => { this.count++; }, 1000); } }this 更灵活”——它只是更静态,一旦定义就固定了this 的来源层级发生了偏移。比如在类方法里嵌套一层箭头函数,它的 this 来自类实例;但如果这层箭头函数又嵌套在一个 setTimeout 里的普通函数里,那内层普通函数的 this 就可能意外变成 window。