this 关键字
this 的绑定规则:默认绑定、隐式绑定、显式绑定、new 绑定和箭头函数。
#type / concept
#status / growing
#resource / javascript
#resource / ecmascript
[!info] related notes
this 关键字
this 不是函数自身,也不是词法作用域,而是在函数调用时动态绑定的值。
四种绑定规则
默认绑定
独立函数调用,非严格模式下 this 是 undefined 或全局对象(浏览器中为 window)。
function foo() { console.log(this); }
foo(); // window (非严格模式)
隐式绑定
作为对象方法调用,this 指向调用者。
const obj = { name: 'x', say() { console.log(this.name); } };
obj.say(); // 'x'
显式绑定
通过 call、apply、bind 指定。
function greet() { console.log(this.name); }
greet.call({ name: 'Tom' }); // 'Tom'
new 绑定
构造函数中,this 指向新创建的对象。
function Person(name) { this.name = name; }
const p = new Person('Alice'); // this -> p
箭头函数
箭头函数没有自己的 this,捕获外层 this。
const obj = {
name: 'x',
say: function () {
const f = () => console.log(this.name);
f();
}
};
obj.say(); // 'x'
绑定优先级
从高到低:new > 显式 > 隐式 > 默认
浏览器环境下的常见场景
- 事件处理函数中
this是绑定事件的元素 - 定时器回调中非箭头函数
this是window - 模块顶层
this在 ES Module 中不是window
最容易误解的点
this在定义时不确定,在调用时才确定- 箭头函数的
this在定义时就固定了,和普通函数相反 - 丢失绑定:把对象方法赋给变量后调用,
this会丢失
放回主题图里看
- 函数基础:ecmascript-functions
- new 操作符:js-new
- 闭包捕获变量:ecmascript-closures