-1

i just created an object with an arrow function :

const user={
    fName:"0xN1nja",
    about:()=>{
        return this.fName;
    }
}

now, when i call that arrow function with .call() method, it returns undefined :

a=user.about.call(user);
console.log(a);
>>> undefined

But when i replaced that arrow function with a normal function expression, it returns the value

const user={
    fName:"0xN1nja",
    about:function(){
        return this.fName;
    }
}
a=user.about.call(user2);
console.log(a);
>>> 0xN1nja

what is happening here?

PS : im new to javascript

Abhimanyu Sharma
  • 858
  • 1
  • 9
  • 17
  • 1
    Google for `js arrow functions`, the first output is: Arrow functions don't have their own bindings to this, arguments or super, and should not be used as methods. In your case, you used an arrow function as a method. You can read about it at the top https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – bill.gates Jun 10 '22 at 08:05
  • 1
    Don't use arrow functions as object methods. – Teemu Jun 10 '22 at 08:05
  • 1
    From [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions): "Arrow functions aren't suitable for `call`, `apply` and `bind` methods, which generally rely on establishing a scope." – Robby Cornelissen Jun 10 '22 at 08:06

1 Answers1

1

Arrow functions don't bind to this as function do. That's one of the main reason they were introduced (probably the most important one).

You cannot even bind them.

Radu Diță
  • 13,476
  • 2
  • 30
  • 34
  • 1
    "*Arrow functions don't bind to this as function do*" regular functions don't bind to `this` at all. The value for `this` is determined at call time. The `.bind()` can "set it" but it can also set any other parameters since it does partial application. Thus hinting at the true nature of `this` - it's a hidden argument to the function implicitly passed at call time. – VLAZ Jun 10 '22 at 08:23