ES6 ReactJS class and this scope from callback [duplicate] - javascript

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
I searched StackOverflow for this issue on StackOverflow, but haven't found an answer to this yet, so bear with me if it has already been answered.
I'm defining a class in ES6 (using ReactJS, although this is somewhat irrelevant to the question) as follows. I would like to modify this.size and this._cache from my fetch callback, however it seems I cannot directly manipulate "this" since it refers to another object than the class instantiation, obviously. When defining var that to be bound to this, it does work in referring to the object, but I feel this isn't the ES6 best way to do this:
class MyDataListStore {
constructor(url) {
this.url = url;
this.size = 0;
this._cache = [];
this.getRemoteData();
}
getRemoteData() {
var that = this;
fetch(this.url).then(function(response) {
return response.json();
}).then(function(j) {
that.size = j["total"];
that._cache = j["table"];
});
}
}
I feel like I'm missing something with ES6, that there may be a better way to do this.
Thanks!

This should do it:
getRemoteData() {
fetch(this.url)
.then((response) => response.json())
.then((j) => {
this.size = j.total;
this._cache = j.table;
});
}

Related

JavaScript class property cannot be found [duplicate]

This question already has answers here:
Javascript: Do I need to put this.var for every variable in an object?
(6 answers)
Closed 6 months ago.
I have this snippet of code. I am very new to JavaScript, and I have an error in:
class X {
constructor() {
this.pick = -1;
this.isClosed = false;
this.pline = [];
}
add(mx, my) {
pline.push(Point(mx,my));
}
draw() {
beginShape();
for (let i = 0; i < pline.length; i++) {
p = pline[i];
vertex( p.x, p.y );
}
... //ignore the rest for now
the issue I am getting is: X, line 14:ReferenceError: Can't find variable: pline
I am a little confused because I am initializing it as a class property, so I am not sure why it cannot be found in the draw function. Any help is highly appreciated.
This is because you have scoped pline to this, so it must be this.pline.push.
Also, if you want to use this scope, it's best to use arrow function methods to maintain the scope. Example:
class clazz{
constructor() {
this.something = 1;
}
add = () => {
console.log(this.something);
};
}
pline refers to a variable (either local or global), not a property. If you want to access a property, then you must use this.pline. Although variables and properties seem the same, under the hood they are fairly different because of how JavaScript classes work (which is quite different from most languages).
in your add() function you are referring to "pline.push()", you need to use this.pline.push()

Keyword "this" not accessible (undefined) within class instance in TypeScript [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 1 year ago.
I have the following class:
export class UIDService {
constructor()
{
}
public getDataFromResponse(response: any) {
var companyArray = [];
var searchResult = response["s:Envelope"]["s:Body"].SearchResponse.SearchResult;
if (searchResult) {
var searchResultItems = searchResult.uidEntitySearchResultItem;
try {
Array.isArray(searchResultItems) ? searchResultItems.forEach(function(param) {
companyArray.push(this.getAddress(param.organisation))
}) : companyArray.push(this.getAddress(searchResultItems.organisation))
}
catch(err) {
console.log(err);
}
}
return companyArray;
}
private getAddress(org: any) {
//Do Stuff
//Do Stuff
//Do Stuff
//Do Stuff
}
}
Which leads to the following error.
Cannot read property 'getAddress' of undefined
I know that this is lost in this context but I'm struggling to get this working. I also tried to put "this" into a instance variable in the constructor but non of my tries were successful.
Any hints to get this running?
Help is really appreciated!

Change js object property getter/setter [duplicate]

This question already has answers here:
How to "override" a defined (get-)property on a prototype?
(4 answers)
Closed 2 years ago.
Is it possible to change the value of the property getter of an object?
let's say we have
const autoIncrementer = (function() {
let value = 0;
return {
incr() {
value++
},
get value() {
return value
}
};
})();
function anotherFunctin (){//log smth.}
autoIncrementer.value = anotherFunction;
P.S. I know that this does not do any good, so I just need an explanation of why is this so? and is there any way to achieve this goal?
You can use setter along with getter.
let obj = {
get propName() {
// getter, the code executed on getting obj.propName
},
set propName(value) {
// setter, the code executed on setting obj.propName = value
}
};
About getters/setters usage - read more here

How to use a method in another method (ES6 class) [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
When I use the work method in the doTasks method, I get the error "Uncaught TypeError: Cannot read property 'work' of undefined". I don't exactly understand what is going on.
class Employee {
constructor(name) {
this.name = name;
this.totalWorktime = 0;
}
work(worktime) {
this.totalWorktime += worktime;
}
doTasks(tasks){
tasks.forEach(function(element) {
this.work(element);
});
}
}
doTasks(tasks) {
tasks.forEach((element) => {
this.work(element);
});
}
remove the "function" so this is really "this"
You are in a different closure.
Either use arrow notation (recommended)...
doTask(tasks) {
tasks.forEach((element) => {
this.work(element);
});
}
...or create a reference to the class instance outside the loop.
doTasks(tasks) {
let that = this;
tasks.forEach(function(element) {
that.work(element);
});
}

Accessing properties from inside callback ES2015 [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
I'm using classes in ES2015 identical to the snippet below:
class ProfileManager{
constructor($http){
this._http = $http;
this.profile = {};
}
getUser(profile){
this._http(`/api/users/${user.id}`).then(function(response){
this.profile = response.data;
/*
* Results in exception because "this uses the function's
* "this" instead of the class' "this"
*/
});
}
I know I can remedy this by creating a profile variable outside of the class and using it in the class, but I was wondering if there was a cleaner or more preferred way to use class properties inside of a nested function or callback.
ES6 arrow functions do not override this
class ProfileManager {
constructor($http) {
this._http = $http;
this.profile = {};
}
getUser(profile) {
this._http(`/api/users/${user.id}`).then((response) => {
this.profile = response.data;
});
}

Categories

Resources