DEV Community

Abhishek
Abhishek

Posted on

Need a solution for Closure with this keyword

function outerFun () {
let a = 10;
return function () {
console.log(this.a);
}
}
let fun = outerFun();
fun()

this is pointing to the window.
How can I convert the above closure so that this points to outterFun

Top comments (3)

Collapse
 
digioi profile image
Mike DiGioia

Is there a reason you need this? or is it because you want to access a...

I would suggest thinking arrow function return instead may solve your problem like

function outerFun () {
   let a = 10;
   return () => console.log(a);
}
let fun = outerFun();
fun()
Enter fullscreen mode Exit fullscreen mode
Collapse
 
digioi profile image
Mike DiGioia • Edited

Otherwise you need to bind the variables to an object

function outerFun () {
let a = 10; 
return (function () {
console.log(this.a);
}).bind({ a })
}
let fun = outerFun();
fun()
Enter fullscreen mode Exit fullscreen mode
Collapse
 
digioi profile image
Mike DiGioia

expressed in a slightly different way

function outerFun () {

    function InnerObject() {
        this.a = 10
    }
    let innerObj = new InnerObject()
return (function () {
console.log(this.a);
}).bind(innerObj)
}
let fun = outerFun();
fun()
Enter fullscreen mode Exit fullscreen mode