BeetleJuice BeetleJuice - 1 month ago 9
Javascript Question

Typescript: How to provide arguments to dynamically executed function

export class MyClass {
myFuncA(msg){console.log('A: '+msg); console.log('this: ',this);}

myFuncB(msg){console.log('B: '+msg); console.log('this: ',this);}
}


I have a class instance called
mc
; I need a way to execute a dynamically named function of a
Typescript
class.

This executes the function properly:

export class CallingClass {
constructor(){
let mc = new MyClass();
mc['myFuncA'].call(); // outputs 'A: undefined' 'this: undefined'
}
}


I have 3 questions:


  1. How can I provide arguments?
    mc['myFuncA'].call('message')
    doesn't work

  2. How can I set
    this
    to be the
    CallingClass
    ?
    mc[...].call(...).bind(this)
    errors

  3. How can I set
    this
    to be the
    MyClass
    ?



plunker

Answer

Please read the documentation for Function.prototype.call()

How can I provide arguments? mc['myFuncA'].call('message') doesn't work

Just like normal function call

mc['myFuncA']('message')

or if you really want to use call

mc['myFuncA'].call(mc, 'message')

How can I set this to be the CallingClass? mc[...].call(...).bind(this) errors

pass it to call as first argument

mc['myFuncA'].call(this, 'message')

this is how you use bind

mc['myFuncA'].bind(this)('message')   

How can I set this to be the MyClass?

mc['myFuncA'].call(mc, 'message')

which is

mc['myFuncA']('message')