?以下代码中,执行后输出什么结果呢?
<html>
<body>
</body>
<script>
var a = 123
const foo = () => a => console.log(this.a) // 结果?
var obj1 = {
a: 'obj1'
}
var obj2 = {
a: 'obj2'
}
var bar = foo.call(obj1)
bar.call(obj2)
</script>
</html>
答案是 123

?
原因:
<html>
<body>
</body>
<script>
var a = 123
const foo = () => {
console.log(this);
return a => {
console.log(this);
console.log(this.a)
}
}
var obj1 = {
a: 'obj1'
}
var obj2 = {
a: 'obj2'
}
var bar = foo.call(obj1)
bar.call(obj2)
</script>
</html>

结果都是 this,因为箭头函数 foo 创建时已经绑定全局的 this 对象了也就是 window,foo.call 也无法改变 this 的指向,因此箭头函数的 this 均指向 window。而 var a = 123 就是?window.a = 123。
<html>
<body>
</body>
<script>
const a = 123 // 此处改为 const
const foo = () => a => console.log(this.a)
var obj1 = {
a: 'obj1'
}
var obj2 = {
a: 'obj2'
}
var bar = foo.call(obj1)
bar.call(obj2)
</script>
</html>

此时结果为 undefined,因为 const 定义的变量不会在全局作用域中创建。
?let a = 123 同理。
参考《前端开发核心知识进阶》
|