this的指向在运行时由函数调用方式决定:1. 全局环境中指向window(浏览器)或global(node.js);2. 普通函数调用时非严格模式指向window,严格模式为undefined;3. 作为对象方法调用时指向该对象,但单独引用后调用会丢失绑定;4. 构造函数中指向新创建的实例;5. 箭头函数无独立this,继承外层作用域的this;6. 可通过call、apply、bind显式绑定this指向。关键在于理解调用上下文而非定义位置。

在javaScript中,this 的指向不是在编写时决定的,而是在运行时根据函数的调用方式动态确定。理解 this 的指向是掌握 javascript 的关键之一。以下是 this 的几种常见用法和指向规则。
1. 全局环境中的 this
在全局执行环境中(浏览器中),无论是否严格模式,this 都指向全局对象。
示例:
console.log(this === window); // true(在浏览器中)
2. 函数中的 this
函数内部的 this 取决于函数如何被调用。
- 非严格模式下,独立函数调用时,this 指向全局对象(window)。
- 严格模式下(”use strict”),this 为 undefined。
示例:
function fn() { console.log(this); } fn(); // 非严格模式:window;严格模式:undefined
3. 对象方法中的 this
当函数作为对象的方法被调用时,this 指向该对象。
示例:
const obj = { name: 'Alice', greet() { console.log('Hello, ' + this.name); } }; obj.greet(); // 输出:Hello, Alice
注意:如果将方法赋值给变量再调用,this 会丢失绑定。
const func = obj.greet; func(); // 输出:Hello, undefined(this 指向 window 或 undefined)
4. 构造函数中的 this
使用 new 调用函数时,this 指向新创建的实例对象。
示例:
function Person(name) { this.name = name; } const p = new Person('Bob'); console.log(p.name); // 输出:Bob
5. 箭头函数中的 this
箭头函数没有自己的 this,它的 this 继承自外层作用域(词法作用域)。
示例:
const obj = { value: 42, normalFunc: function() { console.log(this.value); // 正常输出 42 }, arrowFunc: () => { console.log(this.value); // undefined(this 指向外层,通常是 window) } }; obj.normalFunc(); // 42 obj.arrowFunc(); // undefined
6. 显式绑定 this(call、apply、bind)
可以使用 call、apply 或 bind 方法手动指定 this 的指向。
- call(thisArg, arg1, arg2, …):立即调用函数,参数逐个传入。
- apply(thisArg, [argsArray]):立即调用函数,参数以数组形式传入。
- bind(thisArg):返回一个新函数,this 被永久绑定到指定对象。
示例:
function showName(prefix) { console.log(prefix + this.name); } const user = { name: 'Tom' }; showName.call(user, 'Name: '); // Name: Tom showName.apply(user, ['Hi: ']); // Hi: Tom const boundFunc = showName.bind(user); boundFunc('Bound: '); // Bound: Tom
基本上就这些。掌握 this 的核心在于理解函数是如何被调用的,而不是定义在哪里。不同调用方式决定了 this 的指向,尤其要注意箭头函数的特殊性以及显式绑定的使用场景。