Accessing a class method from with function [duplicate] - javascript

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

Related

Javascript "this" not set in function that was passed around [duplicate]

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

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!

JavaScript field access from anonymous function [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 3 years ago.
how can I access a fiel from within an anonymous function inside a method?
like in this example:
class Something {
constructor (){
this.gax = “gax”;
}
doSomething(){
(function () {
console.log(this.gax);
}());
}
}
new Something().doSomething();
this will result in an error that "this" is undefined.
thank you very much in advance, I could not find an answer in the web after searching for hours.
best,
lev
In your anonymous function, this is bound to the function; it no longer refers to the class.
Use an arrow function instead, which doesn't have it's own this binding.
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(() => {
console.log(this.gax);
})();
}
}
new Something().doSomething();
Alternatively, you could use something like .call(), .apply(), or .bind():
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(function() {
console.log(this.gax);
}).call(this);
}
}
new Something().doSomething();
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(function () {
console.log(this.gax);
}).apply(this);
}
}
new Something().doSomething();
You can use apply method. The apply() method calls a function with a given this value

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

How to pass "this" to another object in javascript? [duplicate]

This question already has answers here:
How do I pass the this context to a function?
(5 answers)
Closed 8 years ago.
how to pass "this" to another function ???
function demo1()
{
demo2(this);
}
how to get this object of demo1 into demo2 ???
function demo2()
{
//how to get this object of demo1 into demo2 ???
}
You can do this a number of ways.
Pass it in
You're already doing this, sort of.
function demo1()
{
demo2(this);
}
function demo2(demo1)
{
console.log(demo1);
}
Call it in the current scope
function demo1()
{
// Executes demo2 in scope of demo1
demo2.call(this);
}
function demo2()
{
console.log(this);
}
function demo1()
{
demo2(this);
}
function demo2(data)
{
console.log(data);
}
Check out the details on console.
That's quite easy to do. You can use .call or .apply:
demo2.call(this);
The first argument you provide will be the context (this) used during execution.

Categories

Resources