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);
});
}
Related
This question already has answers here:
"This" within es6 class method [duplicate]
(1 answer)
How to access the correct `this` inside a callback
(13 answers)
Closed last month.
I have a class, in where I have a method that creates a function to be called by some third party library. Inside the function I want to call class members, but the "this" keyword is not set anymore at the moment the function is called. How can I get the this keyword to work inside the function?
I have an oversimplified example:
class myclass
{
printIt(x) {
console.log(x);
}
getFunc() {
return function(x) { this.printIt(x); };
}
}
(new myclass).getFunc()("test");
TypeError: Cannot read properties of undefined (reading 'printIt')
And I also have a solution which I am not happy with, and which I expect can be done in a more elegant way:
class myclass
{
printIt(x) {
console.log(x);
}
getFunc() {
let self = this;
return function(x) { self.printIt(x); };
}
}
(new myclass).getFunc()("test");
class myclass {
printIt(x) {
console.log(x);
}
getFunc() {
return function(x) {
this.printIt(x);
}.bind(this);
}
}
(new myclass).getFunc()("test");
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 1 year ago.
I have the following class:
class Traffic {
constructor(name) {
this.name = name;
}
setEventListeners() {
$("#btn").on('click', function() {
$(this).text(name);
}
}
}
When clicking on the <button id="btn"></button>This throws the error: name is undefined. This makes sense to me as I would normally use this.name to access the object's properties. However, because I am inside jQuery, now this refers to the jQuery object.
How can I access the name property of the Traffic object?
You can just declare a new variable outside the function where this still points to the class instance.
setEventListeners() {
const name = this.name;
$("#btn").on('click', function() {
$(this).text(name);
}
}
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!
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I'm simply trying to access a class method from within a function within another class method so:
class test
{
show()
{
setTimeout(function()
{
this.showInside()
},0)
}
showInside()
{
alert("WORKING")
}
}
var test2 = new test();
test2.show()
I'm obviously doing something wrong, and clearly I can't use this.showInside() within that function, but I can't figure out what I need to do...
Any help?
this depends on the context. Inside setTimeout, this doesn't refer to the instance. Here's a working example :
class test
{
constructor(){};
show(){
setTimeout((function(){ this.showInside() }).bind(this),0)
}
showInside(){
alert("WORKING");
}
}
var test2 = new test();
test2.show();
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