Search code examples
javascriptnode.jsfunctionthisself

Why am I losing the reference to "self" when I call a function with "module_object[function_name]();"?


I have a file tools.js where I have multiple functions:

const another_module = require('another_module');

module.exports = {

    js_call: function(args={}) {
        /*  This function is executed when a JavaScript function should be called
            Call structure:
                args = {
                    'object': 'object.name',
                    'function': 'method_name',
                    'params': ['arg1', 'arg2']
                }
        */
        var self = this;
        var o = null;
        if ('object' in args) {
            if (args.object == 'tools') {
                o = self;
            }
            if (args.object == 'another_module') {
                o = another_module;
            }
        }
        if ('function' in args) {
            if ('params' in args) {
                o[args['function']].apply(null, args['params']);
            } else {
                o[args['function']]();
            }
        }
    },

    loaded_function: function (params={}){
        var self = this;
        self.test_function();            // this does not work here >> self.test_function is not a function 
    },

    test_function: function (){
        console.log('TEST');
    }
}

So if I do this in another module:

const tools = require('tools');

params = {
    'object': 'tools',
    'function': 'loaded_function',
}

tools.js_call(params);

I get the error

self.test_function is not a function

I am wondering if I am losing the self context when I call the function with o[args['function']](); or with o[args['function']].apply(null, args['params']);.

How can I solve or workaround this?

Note: I am using Node.js 8.9.3


Solution

  • If you use apply with self as the first parameter, the functions will run in the same context with self.

    o[args['function']].apply(self, args['params']);