web-interview
web-interview copied to clipboard
[选择题] 54.(单选题)下面代码的输出是什么
const shape = {
radius: 10,
diameter() {
return this.radius * 2;
},
perimeter: () => 2 * Math.PI * this.radius
};
shape.diameter();
shape.perimeter();
A:20 and 62.83185307179586
B: 20 and NaN
C: 20 and 63
D: NaN and 63
答案:B
解析:
请注意, diameter 是普通函数,而 perimeter 是箭头函数。对于箭头函数,this 关键字指向是它所在上下文(定义时的位置)的环境,与普通函数不同!这意味着当我们调用 perimeter 时,它不是指向 shape 对象,而是指其定义时的环境 ( window)。没有值 radius 属性,返回 undefined。