0

I have a generic function which can speak to multiple other functions in appropriate objects is it possible to use a string to call the appropriate function.

 var string = "save";

 var generic = (new function (string) { 

                string."alert()";


               return this;
               })




 var save = (new function (string) { 

    this.alert = (function () {

              alert("your document has been saved")                    

              return this         

              })

        return this 
          })

var notSaved = (new function (string) { 

    this.alert = (function () {

              alert("your document has not been saved")                    

              return this         

              })

        return this 
          })

I am using it for a far more complex set up but here is an example. Is this possible?

3
  • 2
    I have no idea what you're trying to do from this. Commented Nov 5, 2011 at 6:27
  • "Use a string to call the appropriate function"? Would putting your functions in nested objects work so you could call something like generic["save"]["alert"]()? Commented Nov 5, 2011 at 6:32
  • Note that you don't need new function (){} You can use just function (){} Commented Nov 5, 2011 at 6:35

4 Answers 4

1

Sure you can. Try something like this:

window[string].alert();
Sign up to request clarification or add additional context in comments.

Comments

1

Looking at your code it's hard to tell what you're actually trying to achieve. Nonetheless, here are a few ideas that may be relevant.

First, let's make a couple of objects:

var rabbit = {
  name: 'Peter',
  hop: function () {
    return this.name + ' hopped!'
  },
  jump: function () {
    return this.name + ' jumped!'
  }
}

var hairy_maclary = {
  name: 'Hairy Maclary',
  jump: function () {
    return this.name + ' jumped over the fence!'
  }
}

Now, you could define a function which invokes the hop method on whichever object is passed to it:

function hop(object) {
  return object.hop()
}

hop(rabbit) // 'Peter hopped!'

I'm not sure why you'd do this rather than invoking hop directly, but perhaps you want to do extra stuff before or afterwards.

If you wanted to you could create a completely generic function which would invoke a given method on a given object:

function invokeMethod(object, method) {
  object[method]()
}

invokeMethod(hairy_maclary, 'jump') // 'Hairy Maclary jumped over the fence!'

This is a really strange thing to want to do, though. Perhaps you could provide more of an idea of what you're actually trying to do, since your example code is rather odd.

Comments

0

You can enclose your functions within some object so you can access by passing name of the property using some variable (in this case named string), eg. like that:

var string = 'notSaved';
var funcs = {};

funcs.save = new function(){
    this.alert = function(){
        alert('called save.alert()');
    };
    return this;
};

funcs.notSaved = new function(){
    this.alert = function(){
        alert('called notSaved.alert()');
    };
    return this;
};

funcs[string].alert();

See working example on jsfiddle.

If your variables are global (they should not), they are also automatically enclosed within window object, so you can call them also like that: window[string].alert(). This will not work for non-global functions (in this case my solution seems to be the only one not using eval()).

6 Comments

This seems odd to me. Why make things so convoluted? Wouldn't funcs.save = {alert: function(){ alert('called save.alert()') }} achieve the same thing but much more simply?
@davidchambers: " Why make things so convoluted? ": There are different ways to mimic class-like behaviour in JavaScript (by default, JavaScript does not have any " classes ") and OP followed one of these ways - I just followed the same way. From the article I referenced: " It might look a bit confusing if you're not used to it (...) it's an option, when you really want a constructor function that you'll use only once and there's no sense of giving it a name ". What do you think about that? Is it still worth downvoting?
@Tadeck, in software engineering in general, when there are multiple ways to achieve the same thing, you always want to pick the least convoluted from a readability perspective. Other programmers might have to modify your code someday ;) And as we all know, JS gives you a ton of ways to express the same thing ;)
@Ryan: In software engineering I was taught that the best approach is to choose... best solution suited for specific task. And I believe you are not clairvoyant and do not really know why OP has chosen to use this solution. Your solution is useless in at least one case - when the OP wants to be able to define what happens when the object is constructed (in other words: when wants to define code for constructor). Do you agree?
@Tadeck, I didn't say you should use different solutions; I said that if you have multiple ways to express the same thing, then use the more readable form (if it's not too much of a performance hit). In this particular case, there's no need to do any construction, because his alert functions are not making use of this in any meaningful way. He simply needs separate objects that have an alert function defined as a property of the object. Just have him do something like saved = { alert: function() {...} }. That's easier to read and it actually does the same thing as what you're doing.
|
-1

eval("alert('test');");

You can call functions with eval. Even you can declare functions.

eval("function test(){ alert("test");}");

test();

1 Comment

I'd prefer to see answers which promote good programming practice. In some cases eval is necessary, but this is certainly not one of them.

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.