In my code I have the following:
var setTheme = function (color) {
};
function setTheme(color) {
};
The function names are not really the same but I have put the same here. Is there a difference in the two ways of creating a function?
There is a difference. With a function definition, the entire definition is hoisted:
foo(5); // Pops up 5
function foo(n) {
alert(n);
}
Whereas with var, the declaration is hoisted but the assignment is not:
foo(5); // Error!
var foo = function(n) {
alert(n);
};
Another difference I noticed is that on Google Chrome Canary (currently and at least, I haven't tried in many other browsers) in ECMAScript 5 strict mode, a function definition cannot be nested more than one level deep:
!function() {
'use strict';
function Blah() {
function Lol() { // Error.
}
}
}();
So,
JS function for get set
var setTheme = function (color) {
};
If you need a private utility for getting/setting/deleting model values then you can declare a function as a variable like this. This could be useful for assigning a variable upon declaration calculated by a function.
For: simple version
function setTheme(color) {
};
This is the simplest way to declare a function in JavaScript. Say for example, we want to write a simple function called setTheme(color) which simply takes in one parameter color, does a simple color on the object or returns the value. Here are a few ways you might go about doing exactly this.
5 Different ways: interesting read:
http://www.jquery4u.com/jquery-functions/5-ways-declare-functions-jquery/
This has been answered many times. There are many ways to call these. As I understand, the first one is a function assignment, the second one is a function declaration. The first one will hoist setTheme to the top of the closest scope but it won't be defined as a function till it gets where it's actually assigned. The second one will hoist the function setTheme up top so you'll be able to use this function even before it's been declared. IMO, use always the first one.
Related
I have a javascript file in which I write a bunch of jquery functions. I have a function to return the angular scope. I found out that if I were to write the same function twice, the code still executes.
function getngScope()
{
alert(2);
return angular.element($('#data-area')).scope();
}
function getngScope()
{
alert(1);
return angular.element($('#data-area')).scope();
}
When I call getngScope() I get "1" alerted and the scope returned. Why does it have this behavior?
The second definition of an Object overwrites the first one. In general the last definition of an object overwrites all previous definitions.
Functions in JavaScript are Objects:
(function () {}) instanceof Object === true
When you create a new global function f it's equivalent to creating a property in the window object and assigning the function definition to that variable, if you create a function:
function myFun() { console.log('my function') };
and then check the value of window.myFun you'll notice it is the same function as myFun:
window.myFun === myFun // true
You'll also notice that modifying window.myFun changes/overwrites myFun.
E.g.
function myFun() { console.log('myFun') };
myFun(); // Prints: 'myFun'
// Overwrite myFun
window.myFun = function () { console.log('NoFun') };
myFun(); // Prints: 'NoFun'
The second definition of the function takes precedence.
I recommend you read the chapter on Functions from JavaScript: the good parts by Crockford.
functions are data in memory stack, so when you define another function with the same name, it overrides the previous one.
Well obviously you’re not meant to define the same function twice. However, when you do, the latter definition is the only 1 that applies. Try not to do that. Find another way other than giving two functions the same name.
The second function replaced the first function,you could always change this by modifying the name of the function ,if not you can add multiple arguments ..if that is ever needed...and for the explaination to this behaviour,unlike other programming languages javascript doesnt return any errors while being executed..so u can assume that it just corrects itself during the execution by overwriting the function.
Sorry for the rather beginner question. What's the differences of function usage between
$(document).keypress(function() {
//some code
});
and
var somethingElse = function() {
//some code
};
I know the latter is to create a function similar to Java's
public void somethingElse() {
//some code
}
but I always assume the former as anonymous function that act inside a method. Can someone shed me some light regarding this? Thanks.
The first one is a jQuery shortcut to create an event listener.
It's equivalent to:
document.addEventListener('keypress', function() {
// some code
});
More info: http://www.w3schools.com/jsref/met_document_addeventlistener.asp
Now, about named or anonymous functions, what's the difference between
var doSomething = function() {
// some code
};
and this?
function doSomething() {
// some code
}
There's no difference for the developer. Of course there's a difference on memory, but in javascript developers don't have to take care of it.
Actually for the case of an event handler or other techniques that use callback functions, you can pass an anonymous function or a previously declared one, it's exactly the same:
$(document).keypress(doSomething);
or
$(document).keypress(function() {
// some code
});
creates an anon function and passes it to the handler
creates an anonymous function and a variable that references it.
creates a named function - that is hoisted
the hoisted function becomes available to you at any line within your function scope, while the non-hoisted function will be undefined until the line where it is declared runs.
there is no difference between #2 and #3 (other than the hoisting) - some people think that the first one creates an object and the 2nd one is some magical thing, or a global function, but nope - they are both function objects within your scope.
The former is a callback, meaning some instructions that will be executed ONLY as soon as the keypress event in your example is triggered.
Thus, a function's name is not required.
Function expressions, the latter, is mostly used when adding an object's property acting as a method like:
var myObject = {};
myObject.sayHello = function() {
alert("Hello");
}
I am reading the book. Javascript, The good parts by Douglas Crokford. There are examples provided in the book, but I am not able to understand where and how such examples could be useful in practice. I have modified the code here for simplicity.
here are two ways, I can do function assignment to a variable.
example1:
var test= function(ex) {
alert(ex);
};
test(5);
this produces alert box with value of 5
example2:
var test1 = function test2(ex) {
alert(ex);
};
test1(7); //this produces alert box with value of 7
test2(8)//this does not give a alert box
I have defined function test2 but assigned it to test1. why can't I access test2 directly by calling test2(8).
Further I do not see any big advantage in example 2 over example 1. If you there is some difference, and one of them is superior, I would like to hear that.
Thanks
var test1 = function test2(ex) {
console.log(test2);
};
Naming the function gives it the ability to reference itself from within its body.
test2 is visible only to test2 and its child scopes (functions) if any.
You're basically assigning a function with a name to test1, what's called a "named function expression". It's useful to debug your code because the name of the function will appear in the call stack trace rather than "anonymous function".
Functions in JavaScript are objects too, so the identifier for the function is test1 (the function object), but the function itself has a name of test2, so test1.name == 'test2'
The syntax you're referring to is called a named function expression. It is primarily used to support recursion in anonymous functions.
In javascript prior to ECMASCRIPT 5, there are two ways to do recursion when the function is anonymous.
Using arguments.callee:
(function(x){
alert(x);
if (x) {
arguments.callee(x-1);
}
})(10);
Using a named function expression:
(function countdown (x){
alert(x);
if (x) {
countdown(x-1);
}
})(10);
In ECMASCRIPT 5, when strict mode is enabled arguments.callee is no longer supported. Therefore, in ECMASCRIPT 5 strict mode and for future versions of javascript you should use named function expressions to write recursive anonymous function.
Additional answer:
Now you may be wondering, that's not the syntax you're asking about. That syntax looks like:
(function foo () { foo })()
and you were asking about:
var bar = function foo () { foo }
Actually, they're the same. The named function expression syntax applies to function expressions. Which is nothing more than functions declared in expression context.
In javascript, expression context is simply anywhere math is evaluated. Basically, expression context is anything between braces (), anything to the right of the = sign. And anything which needs to be evaluated by an operator.
Apart from the two forms above, the following are also valid named function expressions:
!function foo(){ foo };
0==function foo(){ foo };
0?0:function foo(){ foo };
The way you want it to behave is against the specification. Function declarations must be named, and their name represent variables in the current scope. But function expressions, when named, should not create a variable with their name. Instead, their name becomes available only inside the function.
Some old browsers (e.g. IE8) used to leak the names as variables, see Named function expressions demystified.
Your example 2 is not really an example of proper JavaScript. There are two ways to define a function:
var foo = function(x) { console.log(x); return x; }
and
function foo(x) { console.log(x); return x; }
note that in the first example you are effectively creating an anonymous function first, and then you attach a name ('foo') to that anonymous function object. In the second example, however, you are creating a named function object 'foo' right away.
Also, if you go to console and define first the test2 the way you did it, and then, after it's defined, enter the line var test1 = test2, then you will have both functions available.
You can see the explanation of the deeper technical difference here in another S/O answer, quite upvoted: var functionName = function() {} vs function functionName() {}
I know I can define properties on functions, which can then be accessed from within the function. Right now, the only syntax I can work out involves two statements. Is there a more concise way to express the following:
function myFunc() {
// do some work
}
myFunc.myProp = 0;
I'm not looking for a solution that is fewer characters -- this isn't code golf. I'm asking something more along the lines of "are there different patterns of function declaration that have this other desirable merit?" This is almost about ways to use closures (because I suspect the answer lies there).
Thanks!
Especially if you want to access properties of the function from inside the function itself, you're better off doing this:
var theFunction = function() {
function theRealFunction() {
// the code
if (theRealFunction.something == "not whatever")
// do something
// more code
}
theRealFunction.something = "whatever";
return theRealFunction;
}();
What that does is wrap your function declaration up in an anonymous function. The problem with accessing function properties via the function name is that it must do that by finding the function's name in the surrounding scope. That's kind-of icky, but at least this way it involves a scope that's essentially private. It'll work whether or not the resulting function (returned as the return value of the anonymous function) is assigned to a different variable, passed to a function as a handler function, etc.
This really, really all depends. If you're looking for private variables, then you can easily return a function from the function -- an inner-function will contain access to its parent's scope.
var outer_function = (function () {
var private_var = "secret",
public_var = "public",
inner_function = function () {
return private_var;
};
inner_function.public_var = public_var;
return inner_function;
}());
outer_function now equals inner_function, with the benefit of having access to the enclosed data. Any properties attached to the inner (in the way you did) will now be accessible as public properties of outer.
To this end, you can return, say, a constructor for a class, with public-static properties, with the enclosed vars acting as private-static properties, shared between every instance of the "class" you build.
Not exactly the answer to your question, but if you ever want to read up some different design patterns that can be used when defining a javascript function, this is one of the best articles I've ever read on the topic:
http://www.klauskomenda.com/code/javascript-programming-patterns/
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}
Way 1:
function fancy_function(){
// Fancy stuff happening here
}
Way 2:
var fancy_function = function(){
// Fancy stuff happening here, too.
}
I use the former when I'm just defining a "normal" function that I'm gonna use one or several times and the latter when I'm passing it a callback for another function or so, but it looks to work fine in the both ways.
Is it really a difference in some way?
There is no difference to the function itself, but the latter gives you more flexibility as you have a reference to the function and it is different with regard to how it behaves if overwritten.
This allows you to achieve behaviours with the latter that you cannot achieve with the former; such as the following trick to "override" an existing function and then call the "base":
var myOriginalFunction = function() {
window.alert("original");
}
var original = myOriginalFunction;
var myOriginalFunction = function() {
window.alert("overridden");
original();
}
myOriginalFunction();
This gives you an alert "overridden", followed by an alert "original".
However, if you attempt this with the former notation, you'll find you get stuck in a never ending loop of alert "overidden".
In the first sample you are defining a named function -- that function will always be known by that name. Defining a different function with the same name will be an error (unless you assign to the window property directly). In the second sample, you are defining an anonymous function and assigning it as the value of a variable. You can change the value of the variable to any other function later as desired; losing, of course, any reference to the anonymous function in the process unless you've stored it elsewhere. So, you're not really doing the same thing in both cases, though you can treat it that way if you wish -- and make sure to define the function before it's used in the second case, though that's more a function of variables than functions per se.
function definition
function literal assignment
only difference is you can access the former instantly in certain cases whereas you have to wait for the assignment on the latter.
Don't run this in firebug console/interpreter to test it, rather test on a real html page.
say('spotted');
function say(msg){ alert(msg) }
The above will work, but if you defined a function literal with var say = function(){} below, it would complain that it isn't defined yet.
You can use either depending on the situation, both become the methods of the window object. The later is known as anonymous function.
As far as the function is concerned, they will behave identically.
See here for more details: http://javascript.about.com/library/blfunc.htm
Functions defined with the Function(){} style are available throughout the program, without having to be defined earlier in the code than where they are called. It's called 'hoisting', I believe.
so this works
cow('spotted');
function cow(color){ return 'cow is '+color; }
but this throws an error
cow('spotted');//cow isn't defined yet!
var cow=function(color){ return 'cow is '+color; }