Add JS using JS?



Hello, i'm wondering if its possible to add js code to js code using js :smashy:

I installed annyang .js so i have this code:

if (annyang) {
  // Let's define a command.
  var commands = {
    'hello': function() { alert('Hello world!'); }

  // Add our commands to annyang

  // Start listening.

Which works perfect, because if i open the page, and i say the hello word, it prompts the alert. But i want to add that "words" dynamically not like pre-defined values.

Something like:

Lets say i have a button, and 2 inputs.
When i press the button, i want to add here:

 var commands = {
    // HERE

Something like: 'input1.value': function() { alert('input2.value'); }

So the result be this:

 var commands = {
   'input1.value': function() { alert('input2.value'); }

Thanks!! PS: If comes to your mind a better way to do that instead of my example, please tell me :slight_smile:


I did this:

  var wordrec = properties.word;
  var commands = {
    wordrec: function() { alert('Hello world!'); }

properties.word is the field that hold the "word", im trying to pass that to the function, but seems its not getting the wordrec value.

Its possible to use a variable in a function?

The reason why i think its not getting the wordrec variable is because my editor is not showing me the blue on the wordrec word, inside the commands:

Edit2: I see that i'm trying to put a var inside a var, not a function. Is this possible? I found this in another forum:

var myObject = {
    a_variable_proxy : (function(){ 
        var myvariable = 'hello'; 
        return myvariable; 

But in this case i'm trying to play with the a_variable_proxy any ideas?

So i should re-do the question.
Is possible to add a variable inside another variable?


You mean a dynamic property name? This can be done with the square brackets notation:

var commands = {}
var wordrec = properties.word

commands[wordrec] = function () {/* ... */}

Or directly inside the object literal:

var commands = {
  [wordrec]: function () {/* ... */}

(This latter syntax is relatively new syntax introduced in 2015, so it probably won't work in IE...)


who still using ie? I don't care about that :joy: :joy:

I'll try right now! Just was waiting since the post, keep udating every 5 minutes to get in action.

Thanks! I'll tell you how was gone!

Edit: and yaaay, worked!! Thank you! :heart_eyes: