S. J.
S. J.

Reputation: 1128

Get reference to method function by name?

I want to store a function, internal to the function-object its within, in an object member, but I need to get access to it via name. The code below 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 do to get _ref.fnc = ???? to work properly?

Upvotes: 3

Views: 207

Answers (2)

dfsq
dfsq

Reputation: 193261

You will have to use helper object to put methods as its properties. Then you will be able to 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 can't use this because it points to the object returned from IIFE, however your methods of interest are not properties of this object.

Upvotes: 4

GeoffreyB
GeoffreyB

Reputation: 1839

There's a typo in your 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 doThing function, you are checking for the existency of a _ref.func instead of _ref.fnc

To achieve what you want to do, you need to understand that the functions you are declaring using the "function" are not linked to the class. There's no notion 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'm just showing you one of them) :

MyClassThing.prototype.func_foo = function () {

}

The best thing to do, in your case, would be to set _ref.fnc to func_foo directly. If you want to keep the this context, take a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

Upvotes: 0

Related Questions