JavaScript中this的理解

JavaScript中this的理解
最新回答
〆剩余的表白

2023-01-07 15:36:22

在 JavaScript 中,this 是一个动态绑定的关键字,其指向取决于函数的调用方式。以下是关于 this 的详细解析:

一、this 的基本规则

核心原则:this 指向调用函数的对象。若没有明确调用者,则根据执行环境决定。

二、不同场景下的 this 指向1. 普通函数调用
  • 非严格模式:this 指向全局对象(浏览器中为 window)。function fn() { console.log(this); }fn(); // windowwindow.fn(); // window
  • 严格模式:this 为 undefined。"use strict";function fn() { console.log(this); }fn(); // undefined
2. 对象方法调用

this 指向调用该方法的对象。

const obj = { name: "obj", showName: function() { console.log(this.name); }};obj.showName(); // "obj"3. 构造函数调用

this 指向新创建的对象实例。若显式返回对象,则 this 被替换。

function MyClass() { this.name = "instance"; }const instance = new MyClass();console.log(instance.name); // "instance"function MyClass() { return { name: "override" }; }const instance = new MyClass();console.log(instance.name); // "override"4. 箭头函数

this 继承自外层作用域,调用方式不影响其指向。

const obj = { a: 1 };const fn = () => console.log(this.a);fn.call(obj); // undefined(外层 this 可能是 window)document.onclick = () => console.log(this); // windowdocument.onclick = function() { setTimeout(() => console.log(this), 100); // document(继承外层 this)};三、修改 this 指向的方法1. call、apply、bind
  • call/apply:立即调用函数,修改 this 并传入参数。function sum(x, y) { console.log(this.a + x + y); }const obj = { a: 100 };sum.call(obj, 3, 7); // 110sum.apply(obj, [3, 7]); // 110
  • bind:返回新函数,延迟调用,固定 this。const boundFn = sum.bind(obj, 3, 7);boundFn(); // 110
2. 存储外层 this

通过变量保存外层 this,供内层函数使用。

const obj = { num: 1, showNum: function() { const _this = this; return function() { console.log(_this.num); }; }};obj.showNum()(); // 13. 借用方法
  • 继承效果:通过 apply/call 借用构造函数。function A(name) { this.name = name; }function B() { A.apply(this, arguments); }const b = new B("test");console.log(b.name); // "test"
  • 操作类数组:借用数组方法(如 arguments)。(function() { Array.prototype.push.call(arguments, 3); console.log(arguments); // [1, 2, 3]})(1, 2);
四、经典案例解析案例 1:嵌套函数中的 thisvar name = "window";var obj = { name: "obj", getName: function() { return function() { return this.name; }; }};console.log(obj.getName()()); // "window"

解析:内层函数由全局环境调用,this 指向 window。

案例 2:通过变量固定 thisvar name = "window";var obj = { name: "obj", getName: function() { const _this = this; return function() { return _this.name; }; }};console.log(obj.getName()()); // "obj"

解析:外层 this 被保存为 _this,内层函数引用它,指向 obj。

五、总结
  • 默认绑定:非严格模式指向全局对象,严格模式为 undefined。
  • 隐式绑定:由对象调用时指向该对象。
  • 显式绑定:通过 call/apply/bind 强制指定 this。
  • 箭头函数:this 继承自定义时的外层作用域。
  • 特殊情况:构造函数返回对象时,this 被替换。

理解 this 的关键在于分析函数的调用方式执行上下文。通过实践和案例分析,可以逐步掌握其动态绑定的特性。