0

I'm experimenting with running a function from a dynamic string...

say I have several functions and i don't want to use 'if else' or inline...

yes()
no()
maybe()
sometimes()
whoknows()
random()

so I am trying this:

window['yes']();

but I am stuck with namespace. as I get the error 'global has no method yes' I am not sure how to tell what namespace i am in.

$(document).ready(function(){

    function yes(){console.log('yes?');}

    window['yes']();

    });

How do I find out or set the current namespace?

If I did set the namespace how do I start running the code in it immediately or does that just happen on its own?

Ben Muircroft
  • 2,936
  • 8
  • 39
  • 66
  • As a sidenote, this looks like a really bad idea, and you're probably doing something wrong if this is the only solution to whatever problem you're having ? – adeneo Nov 20 '13 at 18:22
  • that would be off topic – Ben Muircroft Nov 20 '13 at 18:23
  • I couldn't understand the problem. "this" always returns not the current scope, but of the callee (who called the function). What you try to achieve? – deb0rian Nov 20 '13 at 18:23
  • I'm trying to build an api where I receive messages with dynamic function names – Ben Muircroft Nov 20 '13 at 18:24
  • can you make jsfiddle – Techsin Nov 20 '13 at 18:25
  • I'm only having a problem with a function not being in windows scope, just have no idea how to find out what the current namespace is – Ben Muircroft Nov 20 '13 at 18:28
  • If you are not sure which scope you are in, then you can use console.log(this) to see. In your example 'this' would obviously not contain the method 'yes' since it is never added to 'this'. – Adam Nov 20 '13 at 18:28
  • what is the function 'yes' added to if its not in window and not in this? – Ben Muircroft Nov 20 '13 at 18:30
  • look at this one: http://stackoverflow.com/a/1723340/990434 – Ben Muircroft Nov 20 '13 at 18:34
  • 1
    'yes' is a local variable in the anonymous function you define. And when this anonymous function is called it is bound to the document object. You would have to use `this.yes = function(){};`, but it is not a good idea to add methods to the document object unless you are sure about what you are doing. – Adam Nov 20 '13 at 18:34
  • Thanks Adam, your correct, I've learned something new! – Ben Muircroft Nov 20 '13 at 18:38

0 Answers0