2 分钟内完成 JS 面试 / 这个🤯
问题:
解释this
JavaScript 中的关键字。
快速回答:this
关键字引用当前执行上下文。
更长的答案:this
根据调用的位置不同,工作方式也不同。
this
如果在全局上下文中使用,它将引用window
浏览器中的对象和global
节点中的对象。
// browser
console.log(window.a) // undefined
this.a = 1
console.log(window.a) // 1
// node
console.log(global.a) // undefined
this.a = 1
console.log(global.a) // 1
对于功能而言,它的工作方式类似,但对于模式而言仍然有点不同strict
。
function f1() {
return this // default to global context
}
function f2() {
'use strict';
return this // undefined
}
箭头函数也有自己的技巧,它们总是引用封闭this
。我们将在下一节中详细介绍。
let f1 = function() {
return this
}
let f2 = () => this
console.log(f1(), f2()) // Window, Window
let obj = { f1, f2 }
console.log(obj.f1(), obj.f2()) // obj reference, Window
// ^^^ f1 changed reference, but f2 didn't
至于类上下文,this
指的是对象本身
class Tmp {
a = 10
method() {
console.log(this)
}
}
let tmp = new Tmp()
tmp.method() // Tmp {a: 10}
感觉这些是最常见的情况,但还有更多的极端情况,请查看mdn。
实际应用:
我认为最常见的警告之一this
是当你使用回调时,回调在 React 和 Angular 中也很流行。
class User {
_say(text) {
console.log(text)
}
sayHello() {
this._say('Hello world')
}
sayHi = () => this._say('Hi!')
}
let user = new User()
user.sayHi() // Works
user.sayHello() // Works
setTimeout(user.sayHi, 1000) // Works
// callback will show an error, because `this` reference will change
// Uncaught TypeError: this._say is not a function at sayHello
setTimeout(user.sayHello, 1000)
所以要小心并注意安全!
资源:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
其他帖子:
顺便说一句,我会在这里和推特上发布更多有趣的东西。我们做个朋友吧👋
鏂囩珷鏉ユ簮锛�https://dev.to/hexnickk/js-interview-in-2-minutes-this-3hlm