面试题答案
一键面试- 直接调用
- 在JavaScript中,当函数直接调用时,在非严格模式下,
this
指向全局对象(浏览器中是window
,Node.js中是global
);在严格模式下,this
是undefined
。 - 示例代码:
- 在JavaScript中,当函数直接调用时,在非严格模式下,
// 非严格模式
function directCall() {
console.log(this);
}
directCall(); // 在浏览器中输出window对象
// 严格模式
function strictDirectCall() {
'use strict';
console.log(this);
}
strictDirectCall(); // 输出undefined
- 作为对象方法调用
- 当函数作为对象的方法调用时,
this
指向调用该方法的对象。 - 示例代码:
- 当函数作为对象的方法调用时,
const obj = {
name: 'example',
method: function () {
console.log(this.name);
}
};
obj.method(); // 输出 'example'
- 使用
call
/apply
/bind
调用call
方法:call
方法允许显式设置函数调用时this
的指向,它接受一个this
值和一系列参数。- 示例代码:
function greet(greeting) {
console.log(greeting + ', I am'+ this.name);
}
const person1 = { name: 'Alice' };
const person2 = { name: 'Bob' };
greet.call(person1, 'Hello'); // 输出 'Hello, I am Alice'
apply
方法:apply
方法与call
类似,不同之处在于它接受一个this
值和一个参数数组。- 示例代码:
function sum(a, b) {
return a + b;
}
const numbers = [1, 2];
const result = sum.apply(null, numbers); // 输出3
bind
方法:bind
方法创建一个新的函数,在调用时this
被绑定到指定的值,并且可以预设部分参数。- 示例代码:
function multiply(a, b) {
return a * b;
}
const double = multiply.bind(null, 2);
const result2 = double(3); // 输出6
- 处理兼容性确保
this
指向符合预期- 对于旧版本浏览器不支持
Function.prototype.bind
的情况,可以自己实现一个bind
方法。 - 示例代码:
- 对于旧版本浏览器不支持
if (!Function.prototype.bind) {
Function.prototype.bind = function (context) {
if (typeof this!== 'function') {
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
const self = this;
const args = Array.prototype.slice.call(arguments, 1);
return function () {
const innerArgs = Array.prototype.slice.call(arguments);
return self.apply(context, args.concat(innerArgs));
};
};
}
// 使用自定义的bind方法
function greet2(greeting) {
console.log(greeting + ', I am'+ this.name);
}
const person3 = { name: 'Charlie' };
const boundGreet = greet2.bind(person3, 'Hi');
boundGreet(); // 输出 'Hi, I am Charlie'
通过上述方式,在不同的函数调用方式下,可以确保this
的指向符合预期,并且在处理兼容性时,通过自定义实现部分方法,让代码在旧环境中也能正常工作。