Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrow functions in closures

Why this is working:

var a = () => { 

    var print = function(i) { console.log(i); return this; }    
    var print2 = function(i) { console.log(i); return this; }

    return { print:print , print2:print2 }
}

a().print(5).print2(5);

this is also working:

var b = () => { 

    var print = (i) => { console.log(i); return this; }    
    return { print:print}
}
b().print('Arrow function works');

while this is not working:

var b = () => { 

    var print = (i) => { console.log(i); return this; }    
    var print2 = function(i) { console.log(i); return this; }

    return { print:print , print2:print2 }
}
b().print(5).print2(5);

https://jsfiddle.net/Imabot/1gt2kxfh/14/

like image 576
Fifi Avatar asked Oct 24 '25 04:10

Fifi


2 Answers

It's all due to arrow functions behavior(docs)

Step by step explanation:

var b = () => { 
    // 1
    var print = (i) => { console.log(i); return this; }    
    var print2 = function(i) { console.log(i); return this; }

    return { print:print , print2:print2 }
}
const res = b()
// 2
const secondRes = res.print(5)
// 3
secondRes.print2(5);
  1. here print function saves this reference from the outer scope, so this can't be reassigned anymore
  2. now print function is not using this reference that comes from res variable, because this has already been attached to print function above
  3. as a result secondRes is not going to reference to the object that was returned by b function. But it will use this reference that is attached to print function. And finally because secondRes doesn't have print2 property - it throws
like image 97
Max Avatar answered Oct 26 '25 17:10

Max


In a non-arrow function, the value of this depends on how the function is called. If the function is called as a member of an object, this refers to this object:

someObj.myFunction() // inside myFunction this will point to someObj

In contrast, the arrow functions do not affect this. So whithin an arrow function the value of this is whatever it is in the enclosing scope.

like image 37
lex82 Avatar answered Oct 26 '25 17:10

lex82