Accessing properties from inside callback ES2015 [duplicate] - javascript

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;
});
}

Related

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!

Recursion in Javascript ES6 class [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I am trying to call the same method within a method in a Javascript ES6 class but it is not working.
class Client {
constructor(connection) {
this.channels = [];
this.nickname = null;
this.user = null;
this.realName = null;
connection.on('data', this.parse_message);
}
parse_message(message) {
let messageObject = {};
if (message.includes('\r\n')) {
message = message.split('\r\n');
message.forEach((el) => {
this.parse_message(el);
});
}
else {
message = message.split(' ');
console.log('Message Received: ', JSON.stringify(message));
}
}
}
When ran I get this error TypeError: this.parse_message is not a function. I tried assigning this to a variable self at the top but that still didn't work.
Pass an arrow function as the bound handler so that you can keep this associated with the method.
connection.on('data', (...args) => this.parse_message(...args));
Now your this in the forEach callback will be the expected value.
You can use bind in the constructor:
this.parse_message = this.parse_message.bind(this);
Bind-ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

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);
});
}

ES6 ReactJS class and this scope from callback [duplicate]

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;
});
}

ES 6 Class : Access "this" in another scope [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I have a ES6 Class in NodeJS 4.
In the constructor, I want to modify the prototype of an object, so that it now use this class instance to perform an operation.
But, of course, in the prototype scope, this doesn't refer to the instance of the class i'm creating.
class Generic {
constructor() {
this.myClass = util._extend({}, aClass); //shallow copy
this.myClass.prototype.run = function(fn) {
var str = this.toString;
//in the next line, _this_ should refer to the Generic instance.
this.run(str, fn);
};
}
do() {
return this.myClass;
}
run(str, fn) {
...
}
How can I refer the Generic class instance being created on the myClass prototype scope ?
Some options:
bind:
this.myClass.prototype.run = (function(fn) {
// `this` is the Generic instance.
}).bind(this);
that:
var that = this;
this.myClass.prototype.run = function(fn) {
// `that` is the Generic instance.
};
Arrow functions:
this.myClass.prototype.run = fn => {
// `this` is the Generic instance.
};

Categories

Resources