闭包与this问题求解
来源:6-4 this 有几种赋值情况

慕的地1405430
2020-02-16
var x = 20;
var a = {
x : 15,
fn : function(){
var x = 30;
return function(){
return this.x;
};
}
};
console.log((a.fn())()); // 20
console.log(a.fn()()); //20
console.log(a.fn().call(this)); //20
console.log(a.fn().call(a)); //15
老师可以解释一下这题吗?
写回答
3回答
-
双越
2020-02-16
这个问题,你先别着急问我。你先自己主动思考一下,给你一个思路:
4 行 console.log ,你就一行一行的写自己的理解,尽量详细、傻瓜式的写。写到哪里有问题,你再停下来,针对当前的问题,问我。
按照我的思路,试一试。
----------
PS:我帮你编辑了一下题目内容的格式,用 markdown 的代码块,看起来更舒服一些。
20 -
weixin_慕后端5444640
2020-06-24
var x = 20; var a = { x : 15, fn : function(){ var x = 30; return function(){ return x + ' ' + this.x; }; }, fn2 : function(){ var x = 30; return () => { return this.x; }; } }; console.log((a.fn())()); // 30 20 console.log(a.fn()()); //30 20 console.log(a.fn().call(this)); //30 20 console.log(a.fn().call(a)); //30 15 console.log((a.fn2())()); //15 console.log(a.fn2()()); //15 console.log(a.fn2().call(this)); //15 console.log(a.fn2().call(a)); //15
00 -
张名扬
2020-03-13
我觉得是这样,
第一个(a.fn)()这种自调函数它的this指向都是window,直接调用时根据注意返回的是this.x这个属性。也就是最外层的x 20
第二个this老师说过作为对象的属性调用时指向对象,但是那是在作为对象属性直接调用的情况,这个是在对象属性中使用的闭包实际上就是fn()调用时他返回的是内层函数,fn()()相当于直接调用内层函数,所以他的指向也是window。
第三个的this我也不是很理解
第四个就很好理解了,call(a)指向a this.x就是15
012020-06-19
相似问题