0

I was trying to learn about how to create custom services. As I follow ES6, I used fat arrow.

app.service('randNumGenerator', () => {
    let randNum = Math.ceil(Math.random()*100);
    this.generate = () => randNum;
});

When I have used fat arrow for that anonymous fucntion, it's causing a error saying

angular_v1.7.9.js:15570 TypeError: Function.prototype.bind.apply(...) is not a constructor
    at Object.instantiate (angular_v1.7.9.js:5158)
    at Object.<anonymous> (angular_v1.7.9.js:4994)
    at Object.invoke (angular_v1.7.9.js:5143)
    at Object.enforcedReturnValue [as $get] (angular_v1.7.9.js:4978)
    at Object.invoke (angular_v1.7.9.js:5143)
    at angular_v1.7.9.js:4932
    at getService (angular_v1.7.9.js:5086)
    at injectionArgs (angular_v1.7.9.js:5111)
    at Object.invoke (angular_v1.7.9.js:5135)
    at $controllerInit (angular_v1.7.9.js:11707)
(anonymous) @ angular_v1.7.9.js:15570

Instated of using first is used this by only removing the arrow function

app.service('randNumGenerator', function() {
    let randNum = Math.ceil(Math.random()*100);
    this.generate = () => randNum;
});

But when I removed the fat arrow, it worked fine. What is the actual reason behind this?

Asif Ishtiaq
  • 7
  • 1
  • 5

1 Answers1

0

Fat arrow functions can't always be a substitute for the old-styled function-keyword functions.

The normal functions have their own context, it means that if they're called with new then this points to the object itself, while if they're invoked without new it points to the global object.

Fat arrow functions, instead, can't be used as constructors, this always points to the outer context, and they don't have the Function prototype. It means that bind, call and apply can't be called on them.

In your case, if you receive that error, it means that app.service internally calls bind.