I was writting objects on JavaScript in object notation, and calling methods dynamically like this:
var myObj = {
method1: function(params){
/* decide what other method to call based on an ajax call */
myObj[ajaxCallResult](ajaxCallParams);
},
method2: function(params){
/* do whatever */
},
method3: function(params){
/* do another thing */
}
}
Now I need to rewritte the entire thing in class notation, but I'm having some troubles at this point as I need to call methods dynamically over "this", but I'm getting the error "TypeError: this[myMethod] is not a function.". Obviously there's a function written with that name so I think I can use that way to call methonds when using "this". This is the way I'm using now:
class myObj2 extends myObj1 {
constructor(){
super();
/* do whatever */
}
method1(params){
/* decide what other method to call based on an ajax call */
this[ajaxCallResult](ajaxCallParams);
}
method2(params){
/* do stuff 1 */
}
method3(params){
/* do stuff 2 */
}
}
But this one is definitely not working. Is there a correct way to do what I need in this case?
EDIT 1
As @sabithpocker sugested, here's the ajax code (using jQuery), and yes, the call is in the ajax callback
$.ajax({
method: 'post',
url: url, // from another var
data: data, // created from the params gotten plus a few extras
dataType: 'json'
}).done(function(r){
console.log('r.method -> '+r.method); // definitelly getting what i want
/* Here I tried a few ways: */
this[r.method](r.params); // "TypeError: this.[r.method] is not a function
this.r.method(r.params); // "TypeError: this.r.method is not a function
/* also I assigned this to self in the class constructor (thanks to @Patrick Evans' comment, I consoled log this and it was the $.ajax() object) */
self[r.method](r.params); // same error
self.r.method(r.params); // same error
// surprisingly not getting a "self is not defined" error
});
EDIT 2 (Solved)
As Khauri McClain said, the way was to assign this to a var before the ajax call instead of in the constructor. This is the result:
class myObj{
method1(){
var self = this;
$.ajax({
// conf
}).done(function(r){
self[r.method](r.params);
});
}
method2(params){}
method3(params){}
}