0

Ok so I'm currently trying to create a registration process following a MEAN stack tutorial and I've started using ()=>{} functions over the old syntax.

Now when I used the old syntax as follows

    .controller('regCtrl', function(){
    this.regUser = function(){
      console.log('testing');
    };

    });

The code runs fine and doesn't throw me any errors in the console however when I use the new function syntax

.controller('regCtrl', ()=>{
  this.regUser = ()=>{
    console.log('testing');
  };
});

I receive this in the console log

angular.js:14700 TypeError: Function.prototype.bind.apply(...) is not a constructor
    at Object.instantiate (angular.js:5055)
    at angular.js:11015
    at Object.link (angular-route.js:1214)
    at angular.js:1385
    at wa (angular.js:10545)
    at q (angular.js:9934)
    at f (angular.js:9174)
    at angular.js:9039
    at angular.js:9430
    at d (angular.js:9217) "<h2 ng-view="" class="ng-scope">"

I'm can only assume that this an issue that is within angularjs or that I've syntaxed incorrectly however I am unable to see the issue.

My apologies if this seems like rookie mistake I'm quite an inexperienced coder.

Aravind
  • 40,391
  • 16
  • 91
  • 110
Munerz
  • 1,052
  • 1
  • 13
  • 26

1 Answers1

0

arrows functions don't rebind this to the function scope. You shouldn't just just arrows functions because it's prettier syntax. There is a reason and when to use the. So in these 2 examples this.regUser are referring to different objects.

An arrow function does not have its own this; the this value of the enclosing execution context is used. Thus, in the following code, the this within the function that is passed to setInterval has the same value as this in the enclosing function

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Jay Lane
  • 1,379
  • 15
  • 28
  • Thank you Sterling and Jay for the answers much appreciated I shall read into these resources now. – Munerz Dec 07 '17 at 14:30
  • no problem this is a common mistake. when it first happened to me i had a greater understanding of scoping and arrow functions afterwards – Jay Lane Dec 07 '17 at 14:35