面试题答案
一键面试函数声明定义普通函数
function add(a, b) {
return a + b;
}
函数表达式定义普通函数
const add = function(a, b) {
return a + b;
};
提升(hoisting)方面的区别
- 函数声明:函数声明会被提升到作用域的顶部,意味着在函数声明之前调用该函数也是可以的。例如:
console.log(add(2, 3));
function add(a, b) {
return a + b;
}
上述代码可以正常执行并输出 5
,因为函数声明 add
被提升到了作用域顶部。
- 函数表达式:函数表达式不会被提升,变量会被提升但值为
undefined
。例如:
console.log(add(2, 3));
const add = function(a, b) {
return a + b;
};
上述代码会报错,因为 add
变量虽被提升但在调用时值为 undefined
,并非函数。
普通函数在 this 指向方面的特点
- 在普通函数中,
this
指向取决于函数的调用方式:- 全局作用域中调用:在全局作用域中调用普通函数,
this
指向全局对象(在浏览器中是window
,在 Node.js 中是global
)。例如:
- 全局作用域中调用:在全局作用域中调用普通函数,
function globalFunc() {
console.log(this);
}
globalFunc();
- **作为对象方法调用**:当普通函数作为对象的方法被调用时,`this` 指向该对象。例如:
const obj = {
name: 'example',
printName: function() {
console.log(this.name);
}
};
obj.printName();
- **通过 call、apply、bind 方法调用**:可以使用 `call`、`apply`、`bind` 方法来改变 `this` 的指向。`call` 和 `apply` 是立即调用函数并改变 `this` 指向,`bind` 是返回一个新函数,新函数被调用时 `this` 指向指定对象。例如:
function greet() {
console.log('Hello, ' + this.name);
}
const person1 = {name: 'Alice'};
const person2 = {name: 'Bob'};
greet.call(person1);
greet.apply(person2);
const greetBob = greet.bind(person2);
greetBob();