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);
Related
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 8 years ago.
I am debugging someones else code now and I am just confused when he defines constructor in these two modes. Is there anything special between the two?
//constructor 1
var MyObject = function(){
};
//constructor 2
var MyObject = function MyObject(){
};
Also, whats the effect of just creating a function just like this.
function MyObject(){};
I am just looking at certain use cases for each.
The different options:
1) Function is not named, so you don't get a function name in MyObject.toString()
var MyObject = function(){};
2) Function is named, so you get a function name in MyObject.toString(), but this is deprecated anyway.
var MyObject = function MyObject (){};
Effectively, there is no practical difference between (1) and (2)
3) Function declaration instead of function expression (See discussion on topic)
function MyObject() {}
This is different from the previous options in that it is in scope before the actual declaration, so the following code works fine:
MyObject();
function MyObject() {}
But, if you try this:
MyObject();
var MyObject = function(){};
You get an error.
I generally just stick to option 1, since it seems to be the most logical
The only difference between the two is the latter you can refer to the function internally by function name (though in your case, they have the same name). In some older IEs, they leaked this name to the surrounding scope.
It's also useful to have it named for things like examining the call stack - the named function is the name which will be used (at least in Chrome's inspector).
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)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the purpose of a self executing function in javascript?
Please, can someone explain to me what does that mean in JS:
var obj = (function(){
// code
})()
Thanks
It is an anonymous function that is immediately executed. It's return value is assigned to obj. For example:
var obj = (function () {
return 10;
}()); //Notice that calling parentheses can go inside or outside the others
console.log(obj); //10
They are often used to introduce a new scope so you don't clutter the scope the code is executing in:
var obj = (function () {
var something = 10; //Not available outside this anonymous function
return something;
}());
console.log(obj); //10
Note that since this is a function expression, and not a function declaration, it should have a semi-colon after the closing curly brace.
It's called an immediately instantiated function. It runs the function, and the returned value is assigned to obj. You can create a scope or class with it, in which you can use closures to keep certain variables private within that scope. See John Resigs page on that subject.
So, if the function looks like this:
var obj = (function(n){
return 2+n;
})(3);
The value of obj would be 5.
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(){
}
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"])