this 指向什么
What does 'this' refer to
看答案Show answer
一句话:this 是调用时决定的, 不是定义时。看「谁调用的」。
四条规则,按优先级从高到低—— 这个顺序是标准答案:
new绑定——new Foo(),this是新创建的对象。- 显式绑定——
call/apply/bind指定的那个。 - 隐式绑定——
obj.fn(),this是obj(看点号左边)。 - 默认绑定—— 都不满足时, 严格模式下是
undefined, 否则是window/global。
箭头函数是例外,它不参与这四条—— 它没有自己的 this, 用的是定义时外层作用域的 this, 而且 call / bind改不了它。
最经典的坑:隐式丢失。const fn = obj.method 之后单独调fn(),点号没了,this 就丢了。 把方法当回调传出去(setTimeout(obj.method)、onClick={this.handle}) 都是这个问题 ——这就是 React 类组件必须在构造器里bind 的原因。
会追问:「DOM 事件回调里 this 是什么?」—— 普通函数是绑定事件的那个元素(等于 e.currentTarget), 箭头函数则是外层的 this。
In one line: this is decided when the function is called, not where it was written. Look at who called it.
Four rules, highest priority first — this order is the model answer:
newbinding — withnew Foo(),thisis the object that was just created.- Explicit binding — whatever you handed to
call/apply/bind. - Implicit binding —
obj.fn()makesthistheobj(look left of the dot). - Default binding — when none of the above applies:
undefinedin strict mode, otherwisewindow/global.
Arrow functions are the exception; they do not play by those four rules — an arrow has no this of its own, it uses the this of the scope it was defined in, and call / bind cannot change that.
The classic trap: the implicit binding gets lost. Do const fn = obj.method and then call fn() on its own — the dot is gone, so this is gone. Handing a method off as a callback (setTimeout(obj.method), onClick={this.handle}) is the same bug — and it is exactly why React class components had to bind in the constructor.
Follow-up: “What is this inside a DOM event handler?” — in a normal function it is the element the listener is attached to (the same as e.currentTarget); in an arrow function it is the outer this.