-2

Is it by design that arrow functions can redefine existing functions behavior? Using jQuery's get (yes, I know) - I'm getting two different values of this inside success depending on whether arrow function is used or not. Can anyone explain why it happens?

var get = (e) => {
    return new window.Promise((resolve, reject) => {
      $.ajax({
        context: {test: 1}, // this
        type: "GET",
        url: "...",
        complete: function () {
          // this is only correct when using old syntax, arrow
          // function would redefine the value of this to the function's parent
        },
        complete: ()=>{ } // Is not working, this is not what I'd expect.
      });
    });
Him1
  • 1
  • 1

1 Answers1

1

Arrow functions were primarily introduced to change the scoping of this which helps to avoid using .bind(this) all the time. It's natural that you get different values

From MDN: Arrow Functions

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target.

The cleaner, more succint syntax is of secondary value. They are certainly not an absolute replacement for function


Now that this is taken out of the equation - you've also got 2 oncomplete callbacks in your example.

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
  • 1
    Exactly. In the same way you can't just blindly swap every `for` loop for an `Array.forEach`, arrow functions aren't supposed to be a drop in nicer looking function syntax. – James Thorpe Sep 22 '17 at 15:42