Home ()=> over function() throwing me an Angular error
Reply: 1

()=> over function() throwing me an Angular error

Munerz
1#
Munerz Published in 2017-12-07 14:12:04Z

This question already has an answer here:

  • What does “this” refer to in arrow functions in ES6? 5 answers

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.

Jay Lane
2#
Jay Lane Reply to 2017-12-07 14:19:14Z

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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.359283 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO