I am little confused about using this in typescript, by looking at this code
class GoogleMapsClass {
public map;
constructor(selector) {
var _this = this;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
_this.map = this.responseText;
}
};
xhttp.open("GET", "/test.php", false);
xhttp.send();
}
}
you can see that I am using a context-switch trick var _this = this;
I don't know if this is proper way to work with class fields in typescript, also I am worried that by using this trick I just duplicated memory so it is not good for performance, and overall code quality (I know that JS is not made for some heavy operations, but still, duplicating objects is most trivial mistake when it comes to optimizing code).
What is the most correct way to handle context switching?
There's no duplicated objects in your code. _this is just a reference to this. In fact, you can avoid _this using an arrow function or binding your function.
bind:
class GoogleMapsClass {
public map;
constructor(selector) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
this.map = xhttp.responseText;
}
}.bind(this);
xhttp.open("GET", "/test.php", false);
xhttp.send();
}
}
Arrow function:
class GoogleMapsClass {
public map;
constructor(selector) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = () => {
if (xhttp.readyState == 4) {
this.map = xhttp.responseText;
}
}
xhttp.open("GET", "/test.php", false);
xhttp.send();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With