0

I am wondering if it is possible to assign a method to a variable in node.js script and then be able to call that method via a . notation (something similar to what require does, except I am not reading this file or method from disk) Instead it can be assigned dynamically.

The thought here is to be able to dynamically change what that method does allowing the script to reference the same variable and call but get a different result when the method is updated.

Curious101
  • 944
  • 2
  • 8
  • 26
  • Your question looks confused but it's probably a duplicate of https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname – Denys Séguret Feb 02 '16 at 15:57

1 Answers1

1

I'm pretty sure that it sounds like you are trying to change a function assigned as an object property at run-time and call. If that is what you are asking, then yes. You can do just that. Consider the following code and comments.

Functions are simply objects that you can pass around like any other object. You can assign them to variables, pass them as arguments, and do whatever else you want with them.

/*jslint node:true devel:true*/

"use strict";

/*
 * Here we define 2 functions that 
 * will simply print to console
 */
function func1() {
    console.log("Hello World");
}
function func2() {
    console.log("Foo bar");
}

// Next we declare an object and a counter
var myObject = {},
    counter = 0;

/*
 * Now we are giving our object a property, "funcToUse"
 * and assigning one of the functions we defined earlier
 * to that property.
 */
myObject.funcToUse = func1;

/*
 * Now we are defining a function that we will have run
 * in a timeout and do so as long as counter is less than 5
 */
function timeoutFunc() {

    /*
     * Here we call the function that we assigned
     * to the property "funcToUse" just as we would
     * normally call any other function with "()"
     */
    myObject.funcToUse();

    /*
     * Now were going to change which function is
     * assigned to the object property.  If it was func1
     * it becomes func2 and vice versa.
     */
    if (myObject.funcToUse === func1) {
        myObject.funcToUse = func2;
    } else {
        myObject.funcToUse = func1;
    }

    // This just restarts the timeout
    if (counter < 5) {
        counter += 1;
        setTimeout(timeoutFunc, 2000);
    }
}

// This bootstraps the timeout
setTimeout(timeoutFunc, 2000);

Output:

Hello World
Foo bar
Hello World
Foo bar
Hello World
Foo bar
zero298
  • 20,481
  • 7
  • 52
  • 83