I have a jquery class within a normal class in javascript. Is it possible to access variables in the scope of the parent class from a callback function in the jquery class?
Use an Arrow Function
An arrow function does not have it's own
this. Thethisvalue of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching forthiswhich is not present in current scope they end up findingthisfrom its enclosing scope.
Normal function syntax
function(param1, param2) {}
Arrow function syntax
(param1, param2) => {}
Usage
const simpleClass = function () {
this.status = "pending";
this.target = jqueryObject;
this.updateStatus = function() {
this.target.fadeOut("fast", () => { // notice the syntax here
this.status = "complete"; // no change required here
});
};
};
Using an Arrow function within a ECMAScript 2015 Class
class simpleClass {
constructor() {
this.status = 'pending';
this.target = jqueryObject;
}
updateStatus() {
this.target.faceOut('fast', () => {
this.status = "complete";
});
}
}
const s = new simpleClass();
s.updateStatus();
Described code works only in modern browsers.