Get a reference to a method function by name?

I want to store a function that is internal to the object-object internally in a member of the object, but I need to access it through the name. The following code makes it easier to understand ...

//MyClassThing.js:

var MyClassThing = (function() {
    var _ref = {obj: undefined, fnc: undefined};

    function setup(domObject, refName) {
        _ref.obj = domObject;
        _ref.fnc = this['func_' + refName]; // <<-- This does not work!!
    }

    function doThing() {
        if(_ref.func)
            _ref.fnc();
    }

    function func_foo() {
        console.log('Foo!');
    }

    return { 
        setup: setup,
        doThing: doThing
    };
})();

      

//index.html

<script>
MyClassThing.setup($('#fooObj'), 'foo');
MyClassThing.doThing();
</script>

      

What do I need to do to get it _ref.fnc = ????

working correctly?

+3


source to share


2 answers


You will need to use a helper object to place the methods in its properties. Then you can refer to them by variable name:

var MyClassThing = (function () {

    var _ref = { obj: undefined, fnc: undefined },
        methods = {};

    function setup(domObject, refName) {
        _ref.obj = domObject;
        _ref.fnc = methods['func_' + refName];
    }

    function doThing () {
        if (_ref.fnc) _ref.fnc();
    }

    methods.func_foo = function () {
        console.log('Foo!');
    };

    return {
        setup: setup,
        doThing: doThing
    };
})();

      



You cannot use this

because it points to an object returned from the IIFE, however your methods of interest are not properties of that object.

+4


source


There is a typo in the code:

var MyClassThing = (function() {
    var _ref = {obj: undefined, fnc: undefined};

    function setup(domObject, refName) {
        _ref.obj = domObject;
        _ref.fnc = this['func_' + refName]; // <<-- This does not work!!
    }

    function doThing() {
        if(_ref.fnc)
            _ref.fnc();
    }

    function func_foo() {
        console.log('Foo!');
    }

    return { 
        setup: setup,
        doThing: doThing
    };
})();

      

In your function, doThing

you are checking for existence _ref.func

instead of_ref.fnc



To achieve what you want to do, you need to understand that the functions you declare with a "function" are not associated with a class. There is no concept of "private member function" in javascript. If you want to bind a function to a class, you need to declare it like this (there are other ways, I'll just show you one):

MyClassThing.prototype.func_foo = function () {

}

      

The best thing in your case would be to set _ref.fnc

in func_foo

directly. If you want to keep the context take a this

look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

0


source







All Articles