How to make variable as callable function? - javascript

I have two variable and one function.
<script>
function myfunction(a1,a2,a3)
{
alert(a1+a2+a3)
}
var fname="myfunction";
var fdata="data1,data2,data3";
</script>
I want to call function from variable values. like this
myfunction('data1','data2','data3')
I know how to call function from variable value.
window[fname](); //this call myfunction()
But don't know how to call function with multiple arguments from variable values?
Give me a solution if you can!

First, you don't have to use the name of a function to keep a reference to it. Just use the function directly:
var fname = myfunction;
Then you can call it:
fname('whatever');
To pass parameters from that string, you'll have to get them out of the string, a process that will depend on how you've combined the values into a string in the first place. In your example, you could split the string on commas to create an array, and then use .apply()
fname.apply(null, fdata.split(','));
The .apply() method accepts an array as the second parameter (the first is a value to be used for this), and then calls the function such that the values of the arguments are the elements of the array.

Just add the arguments between the parentheses
window[fname]('data1', 'data2', 'data3');
To pass dynamically the arguments by using the fdata value, you should use apply (like #Pointy suggests).
window[fname].apply(null, fdata.split(','));

you can modify your code to be something like this maybe:
<script type="text/javascript">
function myfunction(a123) {
// remove the coma if you don't want it.
var completeData = a123.replace(/,/g, "");
alert(completeData);
}
var fname = "myfunction";
var fdata = "data1,data2,data3";
window[fname](fdata);
</script>
I hope it helps.

Related

pass array as function parameter in javascript

I encountered an error while coding in javascript. I want to pass an array as a function parameter from main function to another function, do operations in function and the return edited array.
However, as far as I understood, when I di\o this
var1 = function_1(var2) where var2 is an array, it doesn't actually pass the array to a function.
I want to do this with standard JavaScript library.
Thank you in advance.
To demonstrate how it would work:
var var2 = [1,2,3]
var var1 = function_1(var2)
function function_1(a) {
alert(a)
return a
}

$.each function to add return to an external variable

I have an Array of Strings, which i process with this function:
$.each(lines, processLine);
processLine function returns another string, but i need to combine the strings into one result. The main problem is that i don't want the processLine function to refer to the external variable (named css), it just has to return the result, and do the combination externally. So here's what i did:
var css = '';
css += $.each(lines, processLine);
But css variable ends up with the combinations of the original Arrays elements (not processed), don't know why...
$.each() iterates, $.map() projects. Since you want to project values from your lines, you should use $.map():
var css = $.map(lines, processLine).join("");
The function passed to $.map() is invoked for each item in the array with two arguments: the item itself and its index. Since processLine() takes a line as its first and only argument, we can pass that function directly instead of using an anonymous function as an intermediate.
From there, join() will build a string from our projected array. Passing the empty string as a separator results in simple concatenation.
EDIT: If processLine() does not take a single line argument, then my reasoning above is incorrect and you have to write something like:
var css = $.map(lines, function(line, index) {
return processLine(index, line);
}).join("");
Well you can implement a function like this:
function processLines(lines) {
var resultCss = '';
$.each (lines, function() { resultCss += processLine(this) });
return resultCss;
}
var css = processLines(yourLines);

How to create a custom javascript in-bulit apply method

Lets consider this example:-
function X(){
var Y = function(arg1,arg2){
document.write(arguments.length);
document.write(arg2);
};
Y(arguments);
}
x(1,2,3,4,5);
/*Outputs 1 and undefined respectively.
Because here i am actually passing an array like-object to Y. */
By using apply here i am getting the desired results.
function X(){
var Y = function(arg1,arg2){
document.write(arguments.length);
document.write(arg2);
};
Y.apply(this,arguments);
}
x(1,2,3,4,5) //outputs 5 and 2
I want to create an apply like method that takes an Array of argument and invoke that function by passing arguments as seperate parameter values.
Like:
var arr=[1,2,3,4];
Y.apply_like_method(arr);
//and returns like Y(1,2,3,4)
Given this code:
var arr=[1,2,3,4];
Y.apply_like_method(arr);
//and returns like Y(1,2,3,4)
To make that work:
Function.prototype.apply_like_method = function(args) {
return this.apply(this, args);
}
Disclaimer: For illustration purposes only.
In other words, there's no way around .apply().
Just for shits and giggles using eval.
function myApply(fun, ar){
var i, r = [];
for(i=0; i<ar.length; ++i)
r[i] = 'ar['+i+']';
eval('fun('+r.join(',')+');');
}
You want to use the call method instead. See the MDN. What you are describing though is a hybrid of the call method and apply method; you want the ability to supply parameters individually, but to supply them to the function as an array. That, to my knowledge, doesn't exist currently and it would be easier to use apply/call as it was originally intended, or use a javascript object to pass the params into the function.

Error when get value in javascript?

I have a code js;
<script type="text/javascript">
init_test(500,100);
document.write(init_test[0]);
</script>
but output is wrong, it is not result is 500. How to fix ?
It looks like you intended init_test to be an array. Currently you are attempting to call a function named init_test with two arguments. What you wanted was this:
var init_test = [500, 100]; //init_test is an array with 2 elements
document.write(init_test[0]); //Write the element at index 0
If that's not what you intended, and init_test is a function that you haven't shown in your question, and that function returns an array or an object, you need to assign the return value to a variable and then access the index of that:
var returned = init_test(500, 100);
document.write(returned[0]);
You tried to access on an variable which is maybe only declared within the function 'init_test()'. Define the variable outside your function and I'm sure you will get the correct value.

Executing a function by name, passing an object as a parameter

Here's the problem - I know function by name (and that function has already been loaded form an external script), but I don't have an actual function object avail for me to call. Normally I would call eval(function_name + "(arg1, arg2)"), but in my case I need to pass an object to it, not a string.
Simple example:
var div = document.getElementById('myDiv')
var func = "function_name" -- this function expects a DOM element passed, not id
How do I execute this function?
Thanks!
Andrey
Never use eval, it´s evil (see only one letter difference)
You can simply do:
var div = document.getElementById('myDiv');
var result = window[function_name](div);
This is possible because functions are first class objects in javascript, so you can acces them as you could with anyother variable. Note that this will also work for functions that want strings or anything as paramter:
var result = window[another_function_name]("string1", [1, "an array"]);
You should be able to get the function object from the top-level window. E.g.
var name = "function_name";
var func = window[name];
func( blah );

Categories