闭包题目
2017-03-11 10:38
120 查看
<script> var x = 20; var a = { x: 15, fn: function() { var x = 30; return function() { return x; }; } } console.log(a.fn());//function console.log(a.fn()());//20 console.log((a.fn())());//20 console.log((a.fn())() == a.fn()());//true console.log(a.fn().call(this));//20 console.log(a.fn().call(a));//15 </script>
这道题的难点就是匿名函数的作用域是全局的,所以比闭包里的this指向的应该是window对象。
而a.fn().call(a)则是将this指向a对象,所以输出的x为a.x。
<script> var x = 20; var a = { x: 15, fn: function() { var x = 30; //注意!!!!!! var that = this; return function() { return that.x; }; } } console.log(a.fn());//function console.log(a.fn()());//15 console.log((a.fn())());//15 console.log((a.fn())() == a.fn()());//true console.log(a.fn().call(this));//15 console.log(a.fn().call(a));//15 </script>
这里使用that代替this,那么此时that指向的就是a对象了。
console.log(a.fn().call(this));这句我以为是20,但是输出是15.
正确的理解应该是就算传入this指向全局对象,但是返回的匿名函数里的that还是指向a对象。
<script> var x = 20; var a = { x: 15, fn: function() { var x = 30; return function() { return x; }; } } console.log(a.fn());//function console.log(a.fn()());//30 console.log((a.fn())());//30 console.log((a.fn())() == a.fn()());//true console.log(a.fn().call(this));//30 console.log(a.fn().call(a));//30 </script>
此时匿名函数返回的是x而不是this.x了,所以沿着作用域向上找发现有一个局部变量
var x = 30,于是就输出30。
<script> var x = 20; var a = { x: 15, fn: function() { return function() { return x; }; } } console.log(a.fn());//function console.log(a.fn()());//20 console.log((a.fn())());//20 console.log((a.fn())() == a.fn()());//true console.log(a.fn().call(this));//20 console.log(a.fn().call(a));//20 </script>
显然,此时匿名函数会沿作用域向上找x,发现只有一个全局的变量x,于是就返回20.
相关文章推荐
- 一道闭包题目的做题笔记
- js闭包 一些题目
- 通过经典题目来理解多种闭包实现方式
- 关于JS中的闭包问题的题目
- 一个题目引发的闭包、函数声明以及作用域的简单思考
- JS闭包以及具体题目2
- 什么是闭包?请举例说明(面试题目)
- 最新今日头条面试题目(js闭包、原型、继承、作用域)(2016)
- js闭包面试题目
- [011]前端JS经典题目之闭包
- 作用域闭包、预解释和this关键字综合题目
- js闭包相关题目
- 什么是闭包?请举例说明(面试题目)
- Javascript闭包很好玩的题目
- 通过经典题目来理解多种闭包实现方式
- 闭包题目
- 闭包-小题目
- 阿里笔试题目,闭包与for循环
- 闭包与柯里化的小题目
- 通过经典题目来理解多种闭包实现方式