0

If I replace '=>' with 'function' in the following JavaScript code

            fetch(sendUrl, {
                method: "post",
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: ...
            }).then(response => {
                if (response.status == 200) {
                    return response.json();
                }
                else {
                    this.actionMessage = "Cannot get the response from the server. ': " + response.statusText + "'";
                    this.status = "error";
                }
            }).then ...

so it becomes

            fetch(sendUrl, {
                method: "post",
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: ...
            }).then(function(response) {
                if (response.status == 200) {
                    return response.json();
                }
                else {
                    this.actionMessage = "Cannot get the response from the server. ': " + response.statusText + "'";
                    this.status = "error";
                }
            }).then ...

'this' becomes undefined inside the function and I am getting an error like 'Unable to set a property of undefined or null reference'.

How to make this work?

(I need to replace replace '=>' with 'function', because looks like IE does not understand '=>').

Dmitriano
  • 1,878
  • 13
  • 29

1 Answers1

1

You can bind this

function() {
  // contents
}

to

(function() {
  // contents
}).bind(this)
ZeroCho
  • 1,358
  • 10
  • 23