这是博主面试遇到的面试题的威力加强版
我是个前端菜鸟,你觉得过于简单的话就只能证明你真的很不错,你应该大声的告诉你的朋友。
class Animal{
constructor (name) {
this.props = {
name
}
}
canFly () {
function fly () {
return this.props.name === "bird"
}
if (fly()) {
console.log("fly")
} else {
throw new Error("fly fail")
}
}
}
var props = {
name: "worm"
}
const bird = new Animal("bird")
try {
console.log(bird.canFly())
} catch (err) {
console.log(err)
}
如果大家熟悉this,该题其实不太难,混淆元素过多。
如果你对this的理解停留在第一层:输出fly
如果是第二层:fly fail
其实。。。
最后控制台输出can not read "props" of undefined
是不是在你的意料之中呢?
大致解答一下:
brid实例调用canFly方法
if语句中fly函数执行,没有对象引用fly方法,this应该指向window,但是class声明类其内部是严格模式,严格模式下函数指向全局(比如window)的this会变为undefined,所以就没有props喽,所以直接就报错终止喽,所以就被catch捕捉喽。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。