Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here is my code :
JavaScript
class A {
  
  met(_callback) {
    
    _callback.bind(this)();
  }
  
}

const instanse = new A();

instanse.met(function () {
  console.log(this); // A {}
});

It's clear and "this" refers to class A using function expression.
I want to use 2 different ways inside .met(), function expression and arrow function but "this" doesn't refer class A using arrow function :
JavaScript
class A {
  
  met(_callback) {
    
    _callback.bind(this)();
  }
  
}

const instanse = new A();

instanse.met(() => {
  console.log(this);
});


is there anyway to access class A with this keyword inside the arrow function ?

What I have tried:

JavaScript
class A {
  
  met(_callback) {
    
    _callback.bind(this)();
  }
  
}

const instanse = new A();

instanse.met(() => {
  console.log(this);
});
Posted
Comments
Nathan Minier 30-Jul-18 12:51pm    
Not a good approach for a number of reasons. Is there a compelling reason that you can't do:

instance.met(() => {
console.log(instance);
});
Amirhsnj 30-Jul-18 15:19pm    
I red many articles about this keyword inside arrow function and realized its not possible. I mentioned that ways just for ease of use and clarity when somebody else using the class. Actually the class is part of api and i like open hands for selection(arrow.f or f.expression ) twins flat easy to use.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900