0

I have a module created in JavaScript.

var test = function () {
    var validate = function () {
        alert("fg");
    };
    return {
        validate: validate
    };
}();

Now, can I access the above module using a string? For example:

$(function () {
    var s = "test"; 
    s.validate();   // error  
});

Well, I tried, but no luck so far, because "s" is string. Is there any way to convert this string into above module object and access the validate method?

2
  • You can, if you declare your test function as global. Is it a global function or namespaced? Commented Jun 5, 2015 at 9:30
  • 1
    Could you explain what is the purpose of doing this? I'm not quite sure what you are trying to do here. Commented Jun 5, 2015 at 9:31

3 Answers 3

2

You can make use of eval().

var test = function () {
    var validate = function () {
        alert("fg");
    };
    return {
        validate: validate
    };
}();
$(function () {
    var s = eval("test"); //Here
    s.validate();  
});

For a side note:

Use eval() carefully. From the docs:

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.

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

1 Comment

I think it pertinent to add that you should avoid eval at almost all costs. It is slow and dangerous, and usually indicates a poor design in your code. Instead of incorporating eval, OP should rethink program design.
2

s is a String, so if you want to call validate on s you would have to extend the String prototype

String.prototype.validate = function () {
    return alert("fg")
};

Or

But if you want to create an Object called "Test"

var test = function () {
    var validate = function () {
        alert("fg");
    };
    return {
        validate: validate
    };
}();

$(function () {
    var s = test(); // Here 
    s.validate();   
});

1 Comment

I think you misread the question. Note how the value of the string is the same as the name of the module.
0

Another way to do this is to declare the function as global.

window.test = function () {
  var validate = function () {
    alert("fg");
  };
  return {
    validate: validate
  };
}();


$(function () {
  var s = "test"; 
  window[s].validate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

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.