2

This is the way we can get an array by its index:

var theArray=[];
theArray['something']=="Hello!";
console.log(theArray['something']); //Print "Hello!"

Now imagine the same thing, I have a function and I'm going to call it; Like this:

export class myClass {
    public callByIndex(theIndex:string) {
        //this is how it works:
        this.doSomething()

        //And these are the ways I need to call them:
        this.theIndex //of course error!
        //or
        this[theIndex]; //Another Error! How to do it?
    }

    private doSomething (){
        console.log("Yesss, I called!");
    }
}

let callTest = new myClass();
callTest.callByIndex("doSomething"); //Here I give the method name!

How is it possible?

2
  • Index of what? You need object/array to get value based on given index. this.someArray[theIndex] Commented Apr 30, 2017 at 19:24
  • 1
    @Oen44 I know what you mean, that's why I'm asking, I know about JavaScript object/array that's why I said "like array index", I need to call methods like how we can access arrays by their index. Commented Apr 30, 2017 at 19:29

2 Answers 2

3

First of all, arrays in Javascript are just plain objects ({ }) with interger properties. So to invoke a function using the square brackets, just pass the name of the function you want to execute to it

class Test {
  dummyFunction(arg) {
    console.log('dummyFunction called with argument: ' + arg);
  }
}

let test = new Test();
test['dummyFunction']('this is a string');
Sign up to request clarification or add additional context in comments.

4 Comments

Wisely answer! Great. How is the same thing possible from inside the dummyFunction method? Imagine Test class has another method, and dummyFunction's arg argument job is to call those methods according to the given argument. (the given argument is other methods name)
Then inside dummyFunction just do this[arg]() to execute that particular function assuming that the function with name stored in arg takes no argument
@M98 the square brackets in Javascript is actually a property access syntax, functions are just properties of a given object (or type), the nice thing about the square brackets syntax is that it allows you to pass arbitrary expression to it, if it evaluates to a value which does not resolve to an existing property, undefined is returned
Thank you so much for the great answer. It helped me to learn something new again.
0

If the object is based on an Interface some of the members might not be callable (they are not functions). In this case you must specify exactly which member names are allowed as an index.

Also this only works if the parameter type of the member functions is the same but you can overcome this limitation with type any and check for correct parameters inside your function.



    interface OnlyMethodsIf {
        sayHi: (val: string)  => void;
        sayBye(val: string): string;
    }

    const onlyMethods : OnlyMethodsIf = {
      sayHi: (val: string) : void =>  { /* do some stuff */ },
      sayBye(val: string) : string { return 'someString'}
    }

    //if all members are callable we can just use "keyof OnlyMethodsIf" as  member type
    const callToOnlyMethods = (member: keyof OnlyMethodsIf, val: string) => {
      onlyMethods[member](val);
    }


    interface MixedMembersIf {
        sayHi: (val: string)  => void;
        sayBye(val: string): void;
        word: string; //not a method/function
    }

    const mixedMembers : MixedMembersIf = {
      sayHi: (val: string) : void =>  { /* do some stuff */ },
      sayBye(val: string) : string { return 'someString'},
      word: "Ola",
    }

      //this will not work, "word" is not a callable member of MixedMembersIf
      const callToMixedIncorrectly = (member: keyof MixedMembersIf, val: string) => {
      mixedMembers[member](val);
    }

    // defining which members are callable - 'member: "sayHi" | "sayBye"'
    const callToMixedCorrectly = (member: "sayHi" | "sayBye", val: string) => {
      mixedMembers[member](val);
    }


    //real life use case
    const callMathFunction = (
      type: 'round' | 'ceil' | 'floor' | 'trunc',
      num: number,
    ) => {
      return Math[type](num);
    };


Here is an example of how to overcome same type for function members limitation:

 
    interface OnlyMethodsNoLimits {
        sayHi: (param: any)  => number;
        sayBye(param: any): string;
        sayNothing: () => void;
    }

    const onlyMethodsNoLimits : OnlyMethodsNoLimits = {
      sayHi: (param: any) : number =>  { 
         /* check param type here */ 
        console.log("called 'sayHi', param:", param);
        return param
      },

      sayBye(param: any) : string { 
         /* check param type here */ 
        console.log("called 'sayBye', param:", param);
        return param
        
      },

      sayNothing: () : void =>  { 
        console.log("called 'sayNothing'");
      },

    }

    const callToOnlyMethodsNoLimits = (member: keyof OnlyMethodsNoLimits, param?: any) => {
      return onlyMethodsNoLimits[member](param);
    }

    console.log("sayHi with number param returns:",callToOnlyMethodsNoLimits("sayHi", 53));
    console.log("sayHi with string param returns:",callToOnlyMethodsNoLimits("sayHi", "a string"));
    console.log("sayHi withouth param returns:",callToOnlyMethodsNoLimits("sayHi"));

    console.log("sayBye with number param returns:",callToOnlyMethodsNoLimits("sayBye", 53));
    console.log("sayBye with string param returns:",callToOnlyMethodsNoLimits("sayBye", "a string"));
    console.log("sayBye withouth param returns:",callToOnlyMethodsNoLimits("sayBye"));

    console.log("sayNothing with number param returns:",callToOnlyMethodsNoLimits("sayNothing", "a string"));
    console.log("sayNothing with string param returns:",callToOnlyMethodsNoLimits("sayNothing", 53));
    console.log("sayNothing withouth param returns:",callToOnlyMethodsNoLimits("sayNothing"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.