Recursion in Javascript ES6 class [duplicate] - javascript

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

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!

if I assign a function to variable it is showing error in console [duplicate]

This question already has answers here:
Javascript call() & apply() vs bind()?
(24 answers)
Closed 2 years ago.
let user = {
firstName: 'Testname'
}
function testAlert() {
alert(this.firstName);
}
let funcUser = testAlert.call(user); // Testname
funcUser();
Shows error in console:
Uncaught TypeError: funcUser is not a function
I am not getting why it is showing error.
Thanks
Call and apply will run your function, bind just assign context. In your example you should use bind instead of call.
instead of .call use .bind
let user = {
firstName: 'Testname'
}
function testAlert(){
alert(this.firstName);
}
let funcUser = testAlert.bind(user); // Testname
funcUser();
or you can return a function from the testAlert()
example
let user = {
firstName: 'Testname'
}
function testAlert(){
return function() { alert(this.firstName) }
}
let funcUser = testAlert.call(user); // Testname
funcUser()

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

Is it possible to use => to define objects? [duplicate]

This question already has answers here:
What are the differences (if any) between ES6 arrow functions and functions bound with Function.prototype.bind?
(3 answers)
Closed 7 years ago.
I'm trying to use the arrow-constructor to create an object:
var Countable = (data) => {
return data;
}
But when creating an object:
new Countable(newSubscriptions)
I get the error
Uncaught TypeError: (data) => {
return data;
} is not a constructor
I get the expected output by doing
var Countable = function(data) {
return data;
}
Yes, you can use an arrow function to create new objects:
var Countable = () => {
return {}; // This function returns a new object
};
var o = Countable();
However, you can't instantiate an arrow function, because it doesn't have the [[Construct]] internal method. So using new will throw.

Categories

Resources