1

I need to convert a string called edos.desktop to a variable containing a main function, it needs to be like this:

edos.desktop = {
    main: function() {
        . . .
    },
};

and I need to call the function like this:

var package = "edos.desktop";
. . .
package.main();

but how?

I tried to use the window[package].main(); and this doesn't work!

I tested:

alert(window[package]);

and it shows undefined, and:

alert(window[package].main());

does not show the alert...

please help me!!!

...and I dont want APIs

11
  • "edos.desktop" is input? edos.desktop = { main: function() { . . . }, } is expected output? How is package.main() related to input and output? Commented Feb 17, 2019 at 17:44
  • Is this all in the same file ? Commented Feb 17, 2019 at 17:45
  • i have a function that you need specify the package Commented Feb 17, 2019 at 17:46
  • You want to transform a string to an object containing a function ? what should this function do ? Commented Feb 17, 2019 at 17:46
  • and package = "edos.desktop"; Commented Feb 17, 2019 at 17:46

2 Answers 2

5

If you have control over the string, you cold use eval and take package as string.

var edos = {},
    package = "edos.desktop";

edos.desktop = { main: function() { console.log('main'); } };

eval(package).main();

Or take the window object and reduce the splitted name space.

function getValue(object, path) {
    return path.split('.').reduce((o, k) => (o || {})[k], object);
}
var edos = {},
    package = "edos.desktop";

edos.desktop = { main: function() { console.log('main'); } };

getValue(window, package).main();

Sign up to request clarification or add additional context in comments.

Comments

1

You can use eval(), but depending on situations, there may be subtle bugs and security problems.

In my experience, smart and quick ways are troublemakers. I Suggest that you do something like this:


var package = "edos.desktop";

switch(package){
    case 'edos.desktop':
    console.log("calling edo.desktop.main...");
    edos.desktop.main();
    break;
    case 'Other case':
    ...
}
...
...

3 Comments

its like tis, but for every case: "a.b.c", i want to the function search any variable of type and calls a.b.c.main, if error: (console.log("error on package: "+ package))
"case package: { package.main() }" understand?
i just want compatibility

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.