Javascript Arrow Function Conversion difficulties
CodingBrennan (0)

Hello!

const bro = () => this.d1 + " " + this.d2;

var p1 = {
  d1: "woah",
  d2: "jo"
}
bro.call(p1);

I'm playing around to try and experience Javascript outside of a tutorial setting and I've had some problem with the linked code. Namely it calls "undefined undefined" when I believe it should return "woah jo".

However the code works when I type out the function in full, with some additions:

function bro() {
return this.d1 + " " + this.d2
}

var p1 = {
d1: "woah",
d2: "jo"
}
bro.call(p1);

Anyone able to tell me why d1 and d2 are undefined in the first instance? Not really sure what I've changed fundamentally from the first instance to the code displayed in the second?

Thanks!

You are viewing a single comment. View All
vedprad1 (691)

Before I start my explanations, I just want to share that these functions are not called arrow functions. They are lambda functions.

I am not sure if this is entirely correct, but I think this is the explanation.

If you create a function using the keyword function, the creation will be an instance of the Object new Function(). This object has the method call().

However, Lambda is created from AWS (I think), and because of this, it operates differently from new Function(). Lambda functions do not have the method call().

This would be my best guess, but I am not entirely sure if that is correct.