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);
/
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/Imabot/1gt2kxfh/14/
this
references the scope of b
. While in the function declaration this
refers to it's own scope.
– Mouser
Commented
Jan 25, 2020 at 17:03
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);
print
function saves this
reference from the outer scope, so this
can't be reassigned anymoreprint
function is not using this
reference that es from res
variable, because this
has already been attached to print
function abovesecondRes
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 throwsIn 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.
The answer from Lex82 gives the why. If you want to return the functions, you can use function chaining:
var b = () => {
var print = (i) => { console.log(i); return { print:print , print2:print2 }; }
var print2 = function(i) { console.log(i); return this; }
return { print:print , print2:print2 }
}
b().print(5).print2(5);