Add parameter to a function title [duplicate] - javascript

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);

Related

jQuery dynamic function call [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);

Is it possible to make a function self aware without external input

Background
I want a function keeping track of its own state:
var myObject = {
myFunction: function () {
var myself = this.myFunction;
var firstTime = Boolean(!myself.lastRetry);
if (firstTime) {
myself.lastRetry = Date.now();
return true;
}
// some more code
}
}
The problem with the above code is that the value of this will depend on the site of the function call. I want the function to be able to refer to itself without using:
myObject.myFunction
.bind()
.apply()
.call()
Question
Is it possible to give a function this kind of self awareness independent of its call site and without any help from external references to it?
If you want to store that state on the function instance, give the function a name, and use that name within it:
var myObject = {
myFunction: function theFunctionName() {
// ^^^^^^^^^^^^^^^--------------------- name
var firstTime = Boolean(!theFunctionName.lastRetry);
// ^--------------------------- using it
if (firstTime) {
theFunctionName.lastRetry = Date.now();
// ^------------------------------------------------ using it
return true;
}
// some more code
}
};
You'd do that whenever you want to use a function recursively as well. When you give a name to a function that way (putting the name after function and before (), that name is in-scope within the function's own code. (It's not in-scope for the code containing the function if it's a function expression, but it is if it's a function declaration. Yours is an expression.)
That's a named function expression (where previously you had an anonymous function expression). You may hear warnings about NFEs, but the issues various JavaScript implementations had with them are essentially in the past. (IE8 still handles them incorrectly, though: More in this post on my blog.)
You might consider keeping that state somewhere private, though, via an IIFE:
var myObject = (function(){
var lastRetry = null;
return {
myFunction: function() {
var firstTime = Boolean(!lastRetry);
if (firstTime) {
lastRetry = Date.now();
return true;
}
// some more code
}
};
})();
Now, nothing outside that outer anonymous function can see lastRetry at all. (And you don't have to worry about IE8, if you're supporting stubborn XP users. :-) )
Side note: The unary ! operator always returns a boolean, so your
var firstTime = Boolean(!theFunctionName.lastRetry);
...is exactly equivalent to:
var firstTime = !theFunctionName.lastRetry;
...but with an extra unnecessary function call. (Not that it hurts anything.)
Of course you can, simply give your function an internal named representation and it can refer to itself from there. For example...
var obj = {
doThings:function doThingsInternal(arg1, arg2) {
console.log(arg1, arg2);
for (var arg in doThingsInternal.arguments) {
console.log(arg);
}
}
};
obj.doThings('John', 'Doe');
You could use a simple Closure, if you are not too bent on keeping state existence knowledge within the function. But I guess you don't want that. Another way to do this could be changing the function itself on the first call. Benefits, no/less state variables needed and no costly checks on subsequent calls! -
var myObject = {
myFunction: function () {
// Whatever you wanna do on the first call...
// ...
// And then...
this.myFunction = function(){
// Change the definition to whatever it should do
// in the subsequent calls.
}
// return the first call value.
}
};
You can extend this model to any states by changing the function definition per your state.

Does JS prototype have access to the argument(s) passed to an object during initialization?

Everything is in the the title really... I know that functions created using prototype can't have access to private object data/functions, but what about having access to the arguments that were passed to the object when it was created ?
var Voice = function (word)
{
/*
I know I can obviously do something like : 'this.word = word;'
But I was wondering whether there is a standard way of calling an
argument from within a prototype function without having to do
the above ?
*/
};
Voice.prototype.speak = function ()
{
console.log({{word}});
};
x = new Voice('all I can say is this');
x.speak();
Thanks!
No.
The functions on the prototype weren't defined within the function that the variables are in scope for, so they don't have access to them.
You can store the variable as an object property and then read it back from there.
this.word = word;
Maybe like this:
var Voice = function (word) {
this.init_word = word;
};
Voice.prototype.speak = function (){
console.log(this.init_word);
};
x = new Voice('all I can say is this');
x.speak();

How can I make an object callable as an instance and a function

I'm working on building a collection of prototype helper methods inside a wrapper. However for ease of use, I'd like to be able to call the object as both a new instance and single global instance under the same call.
For example, with jQuery, you can call both "$" and "$()" which can be used differently http://learn.jquery.com/using-jquery-core/dollar-object-vs-function/:
So given the bellow as simple example, how could I do something similar?
(function () {
var myWrapper = function (foo) {
return new helper(foo);
};
var helper = function (foo) {
this[0] = foo;
return this;
}
helper.prototype = {
putVar: function(foo) {
this[0] = foo;
}
}
if(!window.$) {
window.$ = myWrapper;
}
})();
// create an new instace;
var instance = $("bar");
console.log(instance);
// call a prototype method
instance.putVar("foo");
console.log(instance);
// call a prototype method using the same call without new instance
// this doesnt work :(
$.putVar("foo");
// however this will work
window.myLib = $("foo");
myLib.putVar("bar");
http://jsfiddle.net/2ywsunb4/
If you want to call $.putVar, you should define putVar like this:
myWrapper.putVar = function (foo) {
console.log('Work');
}
In your code, the instance and myLib are the same thing, they are both instances created by you.
If you want to call both $.putVar and $(...).putVar, you should add the code I show you above. That means you have to define two putVar functions, one is used like a 'instance' method, while the other one is used like a 'static' method.
If you search through jQuery source code, you will see two each functions defined. That's why you can all both $.each(...) and $(...).each for different usages.

How do I call a dynamically-named method in Javascript?

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);

Categories

Resources