Call javascript functions Dynamically - javascript

i am generating dynamic javascript in which i create few functions for storing value
function get[dynamicname](){
return "some value";
}
i want to call this method in another function to get the values of all functions i created
i have all the dynamicnames which i used to create the functions in the function which i am calling..
function getallfunctionvals(){
for ( var i = 0; i < array.length; i++ ) {
var s="get";
var ss="()";
console.log(s+array[i]+ss);
}
}
this is how i am calling the dynamically generated functions but in the console i am getting the function name as string not the value inside it

Hi look at This post.
One of the answer:
if you know that its a global function you can use:
var functPtr = window[func_name];
//functPtr()
Otherwise replace window with the parent object containing the function.

if defined function is in gloabal scope, you can use
window[s+array[i]]()
So if you have a function like getName. what it will do it will call something like
window["getName"]();

you can use eval function. Eg.
var s = eval("function get(){}; gat();");

first of all:
function get[dynamicname](){
return "some value";
}
will generate error: SyntaxError: Unexpected token [
Since "[" is not allowed in javascript function name and variable.
But you can do this:
function getName () {console.log('Name')};
function getAge () {console.log('Age')};
When you invoke the above functions, you can do this:
var s="get";
var thingToGet = "Name";
var ss="()";
eval(s + thingToGet + ss)
Did I answer your question?

Related

Add parameter to a function title [duplicate]

I am working on dynamically creating some JavaScript that will be inserted into a web page as it's being constructed.
The JavaScript will be used to populate a listbox based on the selection in another listbox. When the selection of one listbox is changed it will call a method name based on the selected value of the listbox.
For example:
Listbox1 contains:
Colours
Shapes
If Colours is selected then it will call a populate_Colours method that populates another listbox.
To clarify my question: How do I make that populate_Colours call in JavaScript?
Assuming the populate_Colours method is in the global namespace, you may use the following code, which exploits both that all object properties may be accessed as though the object were an associative array, and that all global objects are actually properties of the window host object.
var method_name = "Colours";
var method_prefix = "populate_";
// Call function:
window[method_prefix + method_name](arg1, arg2);
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.
I would recommend NOT to use global / window / eval for this purpose.
Instead, do it this way:
define all methods as properties of Handler:
var Handler={};
Handler.application_run = function (name) {
console.log(name)
}
Now call it like this
var somefunc = "application_run";
Handler[somefunc]('jerry');
Output: jerry
Case when importing functions from different files
import { func1, func2 } from "../utility";
const Handler= {
func1,
func2
};
Handler["func1"]("sic mundus");
Handler["func2"]("creatus est");
you can do it like this:
function MyClass() {
this.abc = function() {
alert("abc");
}
}
var myObject = new MyClass();
myObject["abc"]();
Within a ServiceWorker or Worker, replace window with self:
self[method_prefix + method_name](arg1, arg2);
Workers have no access to the DOM, therefore window is an invalid reference. The equivalent global scope identifier for this purpose is self.
I wouldn't recommend using the window as some of the other answers suggest. Use this and scope accordingly.
this['yourDynamicFcnName'](arguments);
Another neat trick is calling within different scopes and using it for inheritance. Let's say you had nested the function and want access to the global window object. You could do this:
this['yourDynamicFcnName'].call(window, arguments);
Just do it
class User
getName()
{
return "dilo";
}
}
let user =new User();
let dynamicMethod='getName';
console.log(user[dynamicMethod]()); //dilo
Hi try this,
var callback_function = new Function(functionName);
callback_function();
it will handle the parameters itself.
A simple function to call a function dynamically with parameters:
this.callFunction = this.call_function = function(name) {
var args = Array.prototype.slice.call(arguments, 1);
return window[name].call(this, ...args);
};
function sayHello(name, age) {
console.log('hello ' + name + ', your\'e age is ' + age);
return some;
}
console.log(call_function('sayHello', 'john', 30)); // hello john, your'e age is 30
Try These
Call Functions With Dynamic Names, like this:
let dynamic_func_name = 'alert';
(new Function(dynamic_func_name+'()'))()
with parameters:
let dynamic_func_name = 'alert';
let para_1 = 'HAHAHA';
let para_2 = 'ABCD';
(new Function(`${dynamic_func_name}('${para_1}','${para_2}')`))()
Run Dynamic Code:
let some_code = "alert('hahaha');";
(new Function(some_code))()
Here is a working and simple solution for checking existence of a function and triaging that function dynamically by another function;
Trigger function
function runDynmicFunction(functionname){
if (typeof window[functionname] == "function" ) { //check availability
window[functionname]("this is from the function it "); //run function and pass a parameter to it
}
}
and you can now generate the function dynamically maybe using php like this
function runThis_func(my_Parameter){
alert(my_Parameter +" triggerd");
}
now you can call the function using dynamically generated event
<?php
$name_frm_somware ="runThis_func";
echo "<input type='button' value='Button' onclick='runDynmicFunction(\"".$name_frm_somware."\");'>";
?>
the exact HTML code you need is
<input type="button" value="Button" onclick="runDynmicFunction('runThis_func');">
Try with this:
var fn_name = "Colours",
fn = eval("populate_"+fn_name);
fn(args1,argsN);

why is my function "donethingy" considered "not declared"?

i have a question, there is a problem with a function in a program that i was doing in javascript.
The function is supposed to work when you click on a paragraph, but when i click, the javascript console throws this: "Uncaught ReferenceError: donethingy is not defined
Line: 1".
JS:
window.onload = function(){
var thy = document.getElementById("thy");
var commanderIssue = document.getElementById("commanderIssue");
var listado = document.getElementById("thaCosa");
var thyLy = document.getElementsByTagName("p");
var nli;
var thyText;
var inserting = "a";
var commander = "b";
thy.onclick = function(){
inserting = "* " + prompt("Create a new item");
nli = document.createElement("p");
thyText = document.createTextNode(inserting);
nli.appendChild(thyText);
listado.appendChild(nli);
thyLy = document.getElementsByTagName("p");
}
thyLy.onclick = function donethingy(){
// thyLy.textDecoration.overline;
alert("done");
}
commanderIssue.onclick = function(){
alert("this thing is");
}
}
With the syntax you've used, the name donethingy doesn't actually become the name of the function because you are assigning the funciton's code directly to the onclick property of thyLy.
You could do this:
// This is a function declaration that associates a name with the function
function donethingy(){
// thyLy.textDecoration.overline;
alert("done");
}
// Then the function can be referred to or invoked by name
thyLy.onclick = donethingy;
But, when you create and assign the function in one statement, the function effectively becomes anonymous as it is stored and accessible via the property you assigned it to.
The decision to create a function declaration or an anonymous function requires you taking the following into account:
Anonymous functions can't easily be reused.
Anonymous functions can't easily be unit tested.
Named functions may require more memory, but can be reused and can be
easily unit tested.
You do not set variables or onclick properties to functions defined as:
obj.onclick = function <name>() {}
You set to anonymous functions, like you did for commanderIssue.onclick.
Just remove the name of the function to make it anonymous:
thyLy.onclick = function() {
alert("done");
}
It's good to remember that there are two ways of defining functions:
Declarations, which are executed when you invoke them:
function donethingy() { ... }
Expressions, which are executed when variable statements are executed:
thyLy.onclick = function() { ... }

How to assign a function with parameters without executing it in javascript?

My objective is to change the border style of button elements when they are clicked with javascript. I made a function setBorder and assigned to the onclick event on all button elements as:
function setBorder(myobj) {
myobj.style.borderStyle = "inset";
}
var menubtn = document.getElementById("menu_btn");
menubtn.onactive = setBorder(menubtn);
The problem here is that the border style is changed as soon as the page loads because when javascript is parsed the function setBorder() is executed due to the brackets (). Another alternative I thought was:
function setBorder() {
this.style.borderStyle = "inset";
}
var menubtn = document.getElementById("menu_btn");
menubtn.onactive = setBorder;
I thought this would take the object menubtn -- but this didn't happen. Why didn't this take the object menubtn?
I think there could be a way in which setBorder could be linked as the prototype object of all button elements. The prototype object would have a function func_SetBorder as it's property. Then we could call the func_setBorder as:
menubtn.onclick = menubtn.func_setborder;
This solution achieves what you're looking for via the use of a function closure.
var buttons = [ ... ]; // An array containing the buttons
for (let b of buttons) {
b.onactive = onActive(b);
}
function onActive(button) {
return function () {
button.style.borderStyle = 'inset';
}
}
Well, in JavaScript, when you use this keyword inside function in this it will points to an object on which you call your function. So, you have your function like this
function myFunc() {
this.do_smth;
}
and then you call it: my_obj.myFunc(), then, inside your myFunc thiswill points to my_obj.
Assume that you want to call your function with another object:
obj_foo.myFunc()
In this case this inside your function will points to obj_foo
If you want to call your function with different objects (but you must be sure that your objects have yhe same properties) its better to use call/apply or bind.
bind will say to your function "this is the scope which you should work with". But you should always bind your function to different objects in case of using this. More pretty and safely way is to use call/apply. You also should call your function with call/apply each time like with bind, but it looks more better.
So, your code should be like this: setBorder.call(menubtn)
What you want is binding or binding arguments. Javascript provides a native way to bind a function. If you want to bind arguments only, you can use this method as quoted from here:
Function.prototype.arg = function() {
if (typeof this !== "function")
throw new TypeError("Function.prototype.arg needs to be called on a function");
var slice = Array.prototype.slice,
args = slice.call(arguments),
fn = this,
partial = function() {
return fn.apply(this, args.concat(slice.call(arguments)));
// ^^^^
};
partial.prototype = Object.create(this.prototype);
return partial;
};
You would use it like this:
function setBorder(myobj) {
myobj.style.borderStyle = "inset";
}
var menubtn = document.getElementById("menu_btn");
menubtn.onactive = setBorder.arg(menubtn);
Or:
function setBorder() {
this.style.borderStyle = "inset";
}
var menubtn = document.getElementById("menu_btn");
menubtn.onactive = setBorder.bind(menubtn);
By CSS
#menuBtn:active{
border-style:inset;
}
By Javascript
You should try the eventlistener property as
menubtn.addEventListener("mousedown", setBorder);
menubtn.addEventListener("mouseup", removeBorder);
and inside the setBorder and removeBorder function you can use this
Assign it to a variable.
var functionName = function () {
//things
}
If you want this to be menubtn in the setBorder function, you need to bind it :
menubtn.onclick = setBorder.bind(menubtn)

Assigning a function to a variable in JavaScript

function abc(){
//multiple variables and functions
a:function(){alert("a")};
}
function test(){
var k=abc();
k.a();
}
In the above case, I have a huge function abc() to be assigned to a variable. I want to call the member functions that are visible, like a() from the variable. Is this possible to implement and please give me a sample code if so.
When you include the parenthesis after your function, you're assigning the result of the function to your variable.
If you want to assign the function itself, just omit the parenthesis:
var k = abc;
k.a();
EDIT
Per #Kuba Wyrostek's answer, and #Pointy's comment, that a() function won't be properly exposed.
You'll need to take a look at the Module Pattern. What you need to do is to assign a function to a variable, and have that function return the functions that you want to be able to use outside of that function. This helps with encapsulation.
It's a little hard to tell from your code in the comment exactly what is the user-generated code, but I'll do my best.
var abc = (function () {
var grabApi,
initialize;
// Just an example of how to assign an existing function
// to a property that will be exposed.
grabApi = SCORM2004_GrabAPI();
// This is an example of how to have a property that will be
// exposed be a custom function passing a parameter.
initialize = function(initString) {
return SCORM2004_GrabAPI().Initialize(initString);
};
return {
getApi: grabApi,
init: initialize
}
}());
You can then use this abc object like this throughout your code. Again, this is trying to give an example of how to do what I think you're trying to do based on your comment.
// Assign the SCORM2004_GrabAPI function to a variable.
var SCORM2004_objAPI = abc.getApi();
// Call the Initialize function with an empty string.
abc.init("");
Hmmm… contrary to #krillgar's answer, I believe you were expecting your abc() to return new object. Something like this:
function abc(){
var privateVar;
return {
//multiple variables and functions
a:function(){alert("a")}
}
}
function test(){
var k=abc();
k.a();
}
You should make it an object. In this way you can access its property a.
var abc ={
a:function(){alert("a")}
}
function test(){
var k=abc;//Ofcrse remove the parenthesis
k.a();
}
test();

How can I get the parameter names of a function stored in a variable?

See this code:
var method = function(service,worker){
//....
}
function getArguments(method){
//what I want is:
//print " the arguments of the method is 'service','worker'"
}
getArguments(method);
How can I get the names of the parameters from the variable?
I know method.arguments will not work when the method is not called.
You can call toString on the function, then use a regular expression to extract the argument list from the function definition. Here's a simple example:
function getArguments(method){
// strip off comments
var methodStr = method.toString().replace(/\/\*.*?\*\/|\/\/.*?\n/g, '');
var argStr = methodStr.match(/\(([^)]*)\)/);
alert(argStr[1].split(/\s*,\s*/g));
}
Demonstration

Categories

Resources