Dynamically call function in javascript [duplicate] - javascript

This question already has answers here:
Calling function inside object using bracket notation
(2 answers)
Closed 6 years ago.
I rather have a seemingly trivial issue, but am not able to figure out an efficient approach.
I have a list of about 50 functions to be called such as :
globalClient.funcA(...)
globalClient.funcB(...)
globalClient.funcC(...)
My code should ideally dynamically create the name of the function (funcA / funcB/ funcC and then proceed to actually call that function. My approach below does not work (please note that these aren't exactly the actual names of the functions. I'm only giving these arbitrary names for simplicity of understanding):
var functionName = 'func'.concat('A');
globalClient.functionName
The second line is where it errors out. Now JS thinks that functionName itself is the name of the function. What I want it to do is resolve functionName to funcA and then call globalClient.funcA(...) instead.
I've thought about implementing a switch / case for this but I'm sure there is a far simpler appraoch. Any ideas?

You could use the bracket notation as property accessor.
globalClient[functionName]()

You can use the [ ] operator for accessing the properties.
var globalClient = {
funcA: function(){
console.log('funcA is called');
}
}
var functionName = 'func'.concat('A');
globalClient[functionName]();

Related

How to use a local variable in javascript function [duplicate]

This question already has answers here:
Javascript: Object Literal reference in own key's function instead of 'this'
(5 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 1 year ago.
Apologies if the terminology is off - javascript isn't my thing.
I have a function:
var input = {
getVal: function () {
return $(this).attr("data-current-val");
},
setVal: function () {
$(this).attr("data-current-val", $(this).val());
},
valHasChanged: function () {
return $(this).val() !== $(this).attr("data-current-val");
}
};
As you can see there is some repetition. Firstly, I repeat the data attribute name several times; secondly, I select a jquery object numerous times.
I've tried to remove the repetition. For instance, in respect of the data attribute, by adding node: "data-current-val" at the top and then calling it with this.node in place of the string. That causes an error, as does trying to define and then use the jquery objectin the same way.
Similarly part of the boolean in valHasChanged $(this).attr("data-current-val"), logically could be replaced by this.getVal but that doesn't seem to work either. Where am I going wrong?!
Any help appreciated.

JavaScript function not working when passing variable instead of hard coded value [duplicate]

This question already has answers here:
Using a string to access a variable
(3 answers)
Closed 3 years ago.
I have a JS function as below
// A simple array where we keep track of things that are filed.
filed = [];
function fileIt(thing) {
// Dynamically call the file method of whatever 'thing' was passed in.
thing.file();
// Mark as filed
filed.push(thing);
}
Now, function fileIt(thing) is working well when called as below
fileIt(AuditForm);
Whereas, its giving error at line thing.file(); when i am trying to pass a variable like below
var formID = obj.id;
fileIt(formID);
Variable formID has same value and i.e. "AuditForm" what's wrong here. Kindly suggest.
If obj.id is the string AuditForm, then you have no choice but to use dynamic property notation on the global window object, or use eval if you didn't declare AuditForm with var on the global scope:
If you declare AuditForm with var on the global scope:
fileIt(window[formID]);
If you don't:
fileIt(eval(formID));
Do note that eval is a very poor option, as if obj.id can be interpreted as other code, e.g. another eval call which will be evaluated, then malicious operations can be performed. Example:
const obj = {
id: "eval('alert(\"Inside an eval script!\")')"
};
eval(obj.id);

What does this notation do? [duplicate]

This question already has answers here:
JavaScript square bracket function call
(5 answers)
Closed 4 years ago.
Sorry for the bad title, but I couldn't come up with something better.
I found the following line of code in a legacy project I have to maintain. However, I have ABSOLUTELY no idea what this does or how it works.
$('.js-legend-input')[operation]('chapter__inputs--hidden');
The variable operation is defined as the following:
const operation = active === 'chapter' ? 'addClass' : 'removeClass';
I can only suspect that this line executes the function addClass and removeClass on the .js-legend-input and works with the parameters in the parentheses. So is this notation just a "shorthand" for:
if(active === 'chapter') {
$('.js-legend-input').addClass('chapter__inputs--hidden');
} else {
$('.js-legend-input').removeClass('chapter__inputs--hidden');
}
Because I know sure as hell I have never seen that before.
You are absolutely correct. It's exactly what it does, plus:
If parameter values change, then you only need to update that one line in legacy code, instead of two in case of the ifs
$('.js-legend-input')[ operation ]( 'chapter__inputs--hidden' ) ;
If a new operation is possible, like for example toggleClass then you don't have to add another if, you can just call it with variable operation = 'toggleClass' . Neat, right?
Yeah you are right, this notation [operation] is called bracket notation and it is used to access object properties along with the dot notation (just having . followed by the property name). The bracket notation allows the usage of variables as property names this is why it is used in this scenario. The variable operation just replaces the name of the property with its value.

How to destructure an object into parameter names [duplicate]

This question already has answers here:
Is there a way to provide named parameters in a function call in JavaScript?
(12 answers)
How to get function parameter names/values dynamically?
(34 answers)
Closed 4 years ago.
I have many functions defined elsewhere that look like this
export function foo(bar1, bar2, bar3, ...) {
// does stuff
}
In the module I am working on I am passed both the function above and an object containing the parameters like this:
// params = {
// bar1: bar1Value,
// bar2: bar2Value,
// bar3: bar3Value,
// ...
// }
function myFunc(foo, params) {
}
I need to call func with the params in the correct order. It is an object not an array so I can't rely on the property order, I need to match up the params to the signature of the function. Is this possible?
Edit to add: There are hundreds of functions that can be passed in, I am trying to avoid refactoring them all, but it seems that it is impossible to look up the parameter names directly. However I've found this which shows it can be done by breaking down the function as a string.
You can access the properties of an object (like "params") either like
params.bar1 or like params["bar1"] and you can get the names of the properties by using Object.keys(params), if thats what your asking for.
See also https://www.w3schools.com/js/js_object_properties.asp and https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Why can't one set an alias to document.getElementById()? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript function aliasing doesn't seem to work
Set document.getElementById to variable
Code would be more efficient if this was possible:
var min = document.getElementById;
and then call document.getElementById() using min().
Not trying to write minified code but in this particular case one can reduce scope lookup and shorten some lines.
Is this a syntax issue or a limiation on the language?
When you call foo.bar() then this is set to foo inside bar
When you copy foo.bar to window.bar then call window.bar(), this is set to window.
getElementById has to operate on a DOM document object.

Categories

Resources