函数与逻辑2026年1月27日星期二

"this" 关键字

解开 JS 中最大的谜团。

广告

查看赞助商以支持 JS Fruggal。

this 是动态的。它的值根据函数如何被调用而改变。

显式绑定

强制上下文

有时你想强制函数使用特定对象作为 this。 我们使用 .call().bind()

const person1 = { name: "Alice" };
const person2 = { name: "Bob" };

function introduce(interest) {
  console.log(`你好,我是 ${this.name},我喜欢 ${interest}`);
}

// 1. Call: 立即调用
introduce.call(person1, "编程"); 

// 2. Bind: 返回一个新函数以供稍后使用
// 在 React 事件处理程序中非常有用!
const bobIntro = introduce.bind(person2);
bobIntro("游戏");

箭头函数

箭头函数不关心绑定。它们只使用周围代码中的 this (词法作用域)。这就是为什么我们在 React 组件中使用它们。

广告

查看赞助商以支持 JS Fruggal。