前端面试题JavaScript篇——2022-09-13

每日3题

34 以下代码执行后,控制台中的输出内容为?

 const num = {
a: 10,
add() {
return this.a + 2;
},
reduce: () => this.a - 2,
};

console.log(num.add());
console.log(num.reduce());

35 以下代码执行后,控制台中的输出内容为?

 var x = 1;
if (function f() {}) {
x += typeof f;
}

console.log(x);

36 以下代码执行后,控制台中的输出内容为?

 function f() {
return f;
}
console.log(new f() instanceof f);
  • 公众号【今天也要写bug】更多前端面试题

答案及解析

34

 // 答案:12 NaN
// 考察普通函数和箭头函数中 this 的区别
// 普通函数中的 this 是运行时决定
// 箭头函数中的 this 是编译时就决定了的
const num = {
a: 10,
add() {
return this.a + 2;
},
reduce: () => this.a - 2,
};

console.log(num.add()); // 隐式绑定:this 指向 num,因此输出 12
console.log(num.reduce());
// 箭头函数:this 指向 window,window 上没有属性 a
// 所以 this.a=undefined,最终输出 NaN

35

 // 答案:1undefined
// 考察类型转换、typeof、加法赋值

var x = 1;
// if 条件中的 function f() {} 是 truthy 值
// 所谓 truthy(真值)指的是在布尔值上下文中,转换后的值为 true 的值
// 所有除 false、0、-0、0n、""、null、undefined 和 NaN 以外的皆为真值
// 关于 truthy 和 falsy 的详细说明,可查阅 MDN 文档
if (function f() {}) {
x += typeof f;
}
// typeof 返回的是一个字符串
// 加法赋值操作符 (+=) 将右操作数的值添加到变量,并将结果分配给该变量。
// 即先使用相加运算(+)得到结果,再赋值
// 相加运算符 (+) 用于对两个操作数进行相加运算,如果操作数中有一方为字符串,
// 则该运算符将两个操作数连接成一个字符串。

console.log(x); // 综上,最终输出 1undefined

36

 // 答案:false
// 考察 new、原型链、instanceof

function f() {
return f;
}
console.log(new f() instanceof f);
// new 运算符:如果构造函数显式返回一个对象,则该对象会覆盖 new 创建的对象
// new f() 得到的对象是 f

// instanceof 方法:判断函数(右)的 prototype 属性是否会出现在对象(左)的原型链上
// new f() instanceof f,即 f instanceof f
// 显然 f 的 prototype 属性不会出现在 f 的原型链上
// f.__proto__ => Function.prototype

标签: Javascript

添加新评论