JavaScript: call a function or call a property through reflection

Is there a way to call a function (or property) of an object through reflection in JavaScript?

Suppose at runtime my code already determined that objectFoo really has a property called "bar". Now that my code knows this, the next thing I want to do is call this. Normally I would do this: var x = objectFoo.bar. But "bar" was defined at runtime, so I need to call it using reflection.

+3
source share
4 answers

EVAL: http://www.w3schools.com/jsref/jsref_eval.asp

Eval javascript, javascript javascript.

, , :

var o = {}
for(att in o){
    alert(o[att]);
}

, , , ( ).

obj["propertyName"] = "new value";
obj["MethodName"]();
+4

JavaScript - , . , :

var x = { 'a': 1 };
x.a += 1;
x['a'] += 1;
console.log(x.a);

: 3.

, , myObject:

var methodName = 'myMethod';

// Invoke the value of the 'myMethod' property of myObject as a function.
myObject[methodName]();
+6

( ) :

SomeClass = function(arg1, arg2) {
    console.log('Your reflection');
}

ReflectUtil.newInstance('SomeClass', 5, 7);

:

var ReflectUtil = {};

/**
 * @param strClass:
 *          class name
 * @param optionals:
 *          constructor arguments
 */
ReflectUtil.newInstance = function(strClass) {
    var args = Array.prototype.slice.call(arguments, 1);
    var clsClass = eval(strClass);
    function F() {
        return clsClass.apply(this, args);
    }
    F.prototype = clsClass.prototype;
    return new F();
};
+4

register:

var funcRegister = {};

:

var callReflectionFunc = function(type, obj) {
    var func = false;
    if(funcRegister[type])
        func = funcRegister[type](obj);

    return func;
}

Fill your register with the functions:

funcRegister['yourtype1'] = function(obj) {
    console.log('your type 2');

    return obj;
}

funcRegister['yourtype2'] = function(obj) {
    console.log('your type 2');

    return obj;
}

Then call it with your type and object where you can put your arguments

callReflectionFunc(type, obj);
0
source

Source: https://habr.com/ru/post/1726374/


All Articles