简单
技术面试0 次浏览

请解释 JavaScript 中的 `this` 关键字。

前端工程师
JavaScriptthis 关键字

答题要点

在 JavaScript 中,`this` 关键字的指向取决于函数的调用方式,它在不同的情况下会有不同的指向。在全局作用域中,`this` 指向全局对象,在浏览器环境中就是 `window` 对象。例如,直接在全局作用域中打印 `this`,会输出 `window` 对象。当函数作为对象的方法调用时,`this` 指向调用该方法的对象。比如,`const obj = { name: 'John', sayHello: function() { console.log(this.name); } }; obj.sayHello();` 这里的 `this` 就指向 `obj` 对象。当函数使用 `new` 关键字作为构造函数调用时,`this` 指向新创建的对象。例如,`function Person(name) { this.name = name; } const p = new Person('Jane');` 这里的 `this` 指向新创建的 `p` 对象。另外,在箭头函数中,`this` 的指向取决于定义时的上下文,而不是调用时的上下文。例如,`const arrowFunc = () => { console.log(this); };` 这里的 `this` 会继承外层作用域的 `this` 值。