Hướng dẫn call function dynamically javascript

As Triptych points out, you can call any global scope function by finding it in the host object's contents.

A cleaner method, which pollutes the global namespace much less, is to explicitly put the functions into an array directly like so:

var dyn_functions = [];
dyn_functions['populate_Colours'] = function (arg1, arg2) { 
                // function body
           };
dyn_functions['populate_Shapes'] = function (arg1, arg2) { 
                // function body
           };
// calling one of the functions
var result = dyn_functions['populate_Shapes'](1, 2);
// this works as well due to the similarity between arrays and objects
var result2 = dyn_functions.populate_Shapes(1, 2);

This array could also be a property of some object other than the global host object too meaning that you can effectively create your own namespace as many JS libraries such as jQuery do. This is useful for reducing conflicts if/when you include multiple separate utility libraries in the same page, and (other parts of your design permitting) can make it easier to reuse the code in other pages.

You could also use an object like so, which you might find cleaner:

var dyn_functions = {};
dyn_functions.populate_Colours = function (arg1, arg2) { 
                // function body
           };
dyn_functions['populate_Shapes'] = function (arg1, arg2) { 
                // function body
           };
// calling one of the functions
var result = dyn_functions.populate_Shapes(1, 2);
// this works as well due to the similarity between arrays and objects
var result2 = dyn_functions['populate_Shapes'](1, 2);

Note that with either an array or an object, you can use either method of setting or accessing the functions, and can of course store other objects in there too. You can further reduce the syntax of either method for content that isn't that dynamic by using JS literal notation like so:

var dyn_functions = {
           populate_Colours:function (arg1, arg2) { 
                // function body
           };
         , populate_Shapes:function (arg1, arg2) { 
                // function body
           };
};

Edit: of course for larger blocks of functionality you can expand the above to the very common "module pattern" which is a popular way to encapsulate code features in an organised manner.

Have you ever had the scenario where you needed to call a function based on a variable?

In my most recent use case, I had an area of dynamic modules and needed to loop over them. Then, if I found one with the right values, I needed to call the function dynamically.

So how does a dynamic function call work?

JS function definition

First, let's start with the code for our JS functions:

function customClick(button) {
  button.addEventListener('click', function (event) {
    alert('custom click');
  });
}

function customUppercase(input) {
  input.addEventListener('keyup', function () {
    input.value = input.value.toUpperCase();
  });
}

Not very exciting functions, but good enough to test with.

For this example we are going to use the following HTML:

<input type="text" data-module="customUppercase" /> <br /><br />
<button type="submit" data-module="customClick">Donebutton>

Dynamically call a Function in JavaScript

Let's start by defining our array of custom objects:

const options = ['Click', 'Uppercase'];

We will now loop over these:

for (let i = 0; i < options.length; i++) {
  console.log(options[i]);
}

Within the modules we need to get all types that have the data-module we are passing:

for (let i = 0; i < options.length; i++) {
  const items = document.querySelectorAll(
    '[data-module="custom' + options[i] + '"]'
  );
  for (let j = 0; j < items.length; j++) {
    // Call function
  }
}

Now, we need to call the function dynamically based on our variable:

for (let i = 0; i < options.length; i++) {
  const items = document.querySelectorAll(
    '[data-module="custom' + options[i] + '"]'
  );
  for (let j = 0; j < items.length; j++) {
    this['custom' + options[i]](items[j]);
  }
}

That's how to dynamically call JS functions based on the value in another variable!

Try the code example in this Codepen

See the Pen Vanilla JavaScript Dynamically Calling a Function by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter