Javascript convert string into function name [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Call a JavaScript function name using a string?
javascript string to variable
I have this code:
var Functionify = function() {
return {
init: function(el, t) {
var els = document.getElementsByClassName(el);
var elsL = els.length;
while(elsL--){
//els[elsL].onclick = els[elsL].getAttribute(t);
els[elsL].addEventListener('click', els[elsL].getAttribute(t), false);
}
}
};
}();
Where el = 'myClassName' and t = 'data-id'
Now, 't' is a string, how can tell the addEventListener function to use 't' (a string) as a function name?

In the global namespace, you would do something like:
this.test = function() {
alert('test');
}
window['test']();
The better option however would be to make your function a method of an object you create rather than of the global window object.

I am not sure why you would do it, put if the function is part of the global scope you can use bracket notation.
window["stringName"]();

Using eval() is considered "evil", especially in the example given by Danila -- any piece of JS will / can be executed within an eval(). The best option as stated by epascarello, is to use square-bracket notation to invoke a named function. It should be noted, however, that windowt will invoke a function in the global namespace -- if the function is the method of an object, you should reference it as such.

Use eval() function
Example:
a = "alert(1)"
eval(a)

Related

declare function name in object, Why? [duplicate]

This question already has answers here:
Why use named function expressions?
(5 answers)
Closed 7 years ago.
Was working on some js code performance and saw this approach:
window.sample = {
foo: function foo(a,b){
// code goes here
}
bar: function bar(a,b){
// code goes here
}
}
is there any reason why you would decelerate the function name after the word "function" ?
dose it help to debug?
is it good or bad or just unnecessary?
The only reason would be that you can use the function itself from within the function without a reference to the object:
foo: function foo(a,b){
return a > 0 ? a + foo(a-1,b) : b;
}
Note howeever that support for named function literals is not consistent across browsers, so you should really avoid using it.
instead of assigning an anonymous function to the foo and bar properties, they are assigning named functions.
it can be helpful for debugging: the only difference this makes, that i know of, is that you will see the names of the functions show up in the call stack instead of "javascript anonymous function"
It's a named function expression. The name of the function is only available as a variable within the function itself. This can be useful for recursion, for example:
var obj = {
foo: function foo(node) {
// Do something to node
var childNode = node.firstChild;
while (childNode) {
foo(childNode);
childNode = childNode.nextSibling;
}
}
};
The name of the function is also available in most browsers via the non-standard name property of the function, which can help identify functions while debugging or examining stack traces.
IE < 9 has a flawed implementation, so you need to exercise care when using it. Full details can be found in Juriy Zaytsev's excellent article on the subject.

JavaScript function different syntax? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the difference between a function expression vs declaration in JavaScript?
This JavaScript syntax I haven't seen till now, what does it do really?
What is the difference between the following two ways of writing a function? I've seen both used, but I'm not sure which one is 'correct'.
function init() {
}
init: function() {
},
And what are the advantages to writing it the second way?
Function declaration
function init() {
}
Function expression
var init = function() {
};
The primary differences have to do with Variable Hoisting in JavaScript. You can read more here: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting and http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
By your example, I believe you are also interested in defining anonymous functions in object literals. Here is an example:
//obj is the object name
var obj = {
//init is the property name or key and the anonymous function is the value
init: function() {
},
anotherProp: 'some value'
};
This would be used like so:
obj.init();
alert(obj.anotherPorp);
In object literals different properties of the object are defined with a key: value syntax and use commas to separate them.
I would recommend going through this free series on JavaScript http://learn.appendto.com/lessons, it will answer a lot of these questions for you and give you a solid base to becoming a JS developer.
The second one can only be used in the context of an object literal:
var myNamespace = {
func1: function () {
// do something
},
func2: function () {
// do something else
},
someValue = 5
};
The first form is executed as a statement. It is equivalent to:
var init = function () {
// do something
};
The first example defines a function in the global scope which can be called with init(). The second defines a property of an object called init that is the function declaration to the right.
Generally, the second example provides a smaller scope in which you could execute the function.
First example allows you to call the function like so:
init();
And the second, more likely this:
var thing = function() {
init: function() { }
};
thing.init();
Try to always use:
init: function (){
}
when writing an object literal.
When you're trying to process a global function set it as a var instead, so:
var init = function(){
}
Remember, each has its place, but I've personally become fond of writing a namespace for the project I'm working on and using an object literal.
Now both of these will only be available in the object as soon as the object is set. The other method is a little sloppier and less used now, but can be called no matter the order of operations, so it can be called before or after it's set in the code... Again, this is being abandoned in a lot of cases.
function init(){
}

Javascript function declaration. When to use what? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}
What is the reason you would do:
somename = function(param1, param2) { }
In stead of doing:
function somename(param1, param2) { }
Well since the 1st syntax is a variable declaration and the 2nd is an actual function declaration, i would stick to the 2nd unless I truly needed the 1st.
Try to read up on scoping and variable hoisting and you will see that the 2nd syntax can sometimes create trouble for you :)
http://www.dustindiaz.com/javascript-function-declaration-ambiguity/
http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
Btw, you might want to browser this thread and look for more good stuff:
var functionName = function() {} vs function functionName() {}
$fn = function(param1, param2)
By using the above form you are able to pass $fn to any function as a parameter, or you could create a new object from that:
function doSomethingWithFn($fn);
or
$fnObject = new $fn(param1, param2)
You can use the second form when you just need a utility function, or for closures:
function utilityFn(str) {
return str.indexOf('a')
}
var str = utilityFn('abc');
or
$('#element').click(function() {
utiliyFn($('#element').html())
})
The first method creates a function object that you can then pass as parameter to other functions. For example, if you want to execute some code when a text box value changes, you can set a callback like this (using jQuery):
var onChange = function() { /* ... */ }
$("#username").change(onChange);

Executing a string without eval or is eval ok to use here? [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Use dynamic variable names in JavaScript
(19 answers)
Closed last year.
Is there a better way of executing the string "getData" without eval or eval a good option in this case since what is being evaluated is not user generated?
object.myMainObject(Marcus)
object = {
Data = {
Marcus : function(){
alert('marcus function')
},
James : function(){
alert('james function')
}
}
myMainObject : function(string){
getData = "object.Data." + string + "()"
eval(getData)
}
}
eval is completely unnecessary for this case, just use the bracket notation to access the dynamically named property:
var object = {
Data : {
Marcus : function(){
alert('marcus function');
},
James : function(){
alert('james function');
}
}
myMainObject : function(string){
var getData = object.Data[string]();
}
};
object.myMainObject("Marcus"); // 'marcus function'
Notes:
There were some syntax errors in the way you were defining object (you were using =, instead of : ).
You weren't using the var statement to declare object nor getData, please, when declaring variables, use the var statement, otherwise, they will end up as properties of the global object.
As a safety measure, you could check if the member that's being accessed is actually a function before calling it, e.g.:
//...
var getData;
if (typeof object.Data[string] == 'function') {
getData = object.Data[string]();
}
//...
It is not ok to eval it.
getData = object.Data[string]()
Yes, there is a better way. Use square bracket notation to access an object's properties by name:
object.Data[string]();
It's ok to eval it. Although I really don't understand what you're trying to achieve.

Ways to call a Javascript function using the value of a string variable? [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 5 years ago.
I've seen this technique for calling a Javascript function based on the value of a string variable.
function foo() {
alert('foo');
}
var test = 'foo';
window[test](); //This calls foo()
Is this the accepted way to do it or is there a better way? Any cross-browser issues to worry about?
Looks fine to me. I would probably create a simple helper function like following:
function runFunction(name, arguments)
{
var fn = window[name];
if(typeof fn !== 'function')
return;
fn.apply(window, arguments);
}
//If you have following function
function foo(msg)
{
alert(msg);
}
//You can call it like
runFunction('foo', ['test']); //alerts test.
I personally wouldn't bother even with a helper function
window[someKey]('test')
would be fine.
However I wouldn't general maintain a set of possible functions to call at the global scope anyway. Hence I would use a more general pattern:-
obj[someKey]('test')
where obj may be this, a property of this or variable from a closure.
You can simply use it like this... (of course substitute the strings with variables where needed)
document["getElementById"]("elementName")["style"]["border"] = "1PX SOLID GREEN";
Which is also easily/usually typed like this of course...
document.getElementById("elementName").style.border = "1PX SOLID GREEN";
Here's another multi-dimensional example...
var myObject = new Object();
myObject["myValue"]["one"] = "first value";
myObject["myValue"]["two"] = "second value";
alert(myObject["myValue"]["two"]); //outputs "second value"
Which could also be written as...
var myObject = new Object();
myObject["myValue"] = {one: "first value", two: "second value"};
alert(myObject["myValue"]["two"]); //outputs "second value"
You can use eval(str)
eval('foo();');
use this with extreme caution.
I have created a function to call a named function. It works both in browser and in Node.js. I have created a gist (https://gist.github.com/netsi1964/3f19bd96f2d6e18bd818) which also contains a small test. The fingerprint of the function is: callFunction(scope, fn, args).
It sets the scope in the function to the specified scope, and defaults to window (in browser) and global (in Node.js).
To answer your original request you would use it like this:
callFunction(window, "foo",["test"])

Categories