面试题答案
一键面试回调函数在JavaScript异步操作中的作用
- 解决异步问题:JavaScript是单线程语言,异步操作(如读取文件、网络请求等)不能阻塞主线程。回调函数允许在异步操作完成后执行特定的代码,避免阻塞,使程序继续执行其他任务。
- 控制流程:通过将回调函数作为参数传递给异步函数,异步操作完成时,会调用该回调函数,从而控制异步操作完成后的流程走向。
使用箭头函数作为回调函数简化代码示例
例如在setTimeout
中,普通函数写法如下:
setTimeout(function() {
console.log('普通函数作为回调');
}, 1000);
使用箭头函数简化后:
setTimeout(() => console.log('箭头函数作为回调'), 1000);
箭头函数与普通函数在this指向方面的区别
- 普通函数:
this
的指向取决于函数的调用方式。在全局作用域中,this
指向全局对象(浏览器中是window
,Node.js中是global
)。当函数作为对象的方法调用时,this
指向该对象。例如:
const obj = {
value: 10,
printValue: function() {
console.log(this.value);
}
};
obj.printValue(); // 输出10,此时this指向obj
- 箭头函数:箭头函数没有自己的
this
,它的this
继承自外层作用域。无论在何处调用,箭头函数的this
始终指向其定义时所在的作用域中的this
。例如:
const outerThis = this;
const arrowFunction = () => console.log(this === outerThis);
arrowFunction(); // 输出true
在ES6类的方法中使用箭头函数需要注意,由于箭头函数没有自己的this
,它不会指向类的实例,而是继承外层作用域的this
,可能导致错误的行为。例如:
class MyClass {
constructor() {
this.value = 20;
}
// 错误示例
wrongPrint = () => console.log(this.value);
// 正确示例
correctPrint() {
console.log(this.value);
}
}
const myObj = new MyClass();
myObj.wrongPrint(); // 这里this指向外层作用域,可能不是期望的MyClass实例
myObj.correctPrint(); // 这里this指向MyClass实例