views:

242

answers:

8

Are the JavaScript code snippets given below some sort of function declaration? If not can someone please give an overview of what they are?

some_func = function(value) {
    // some code here
}

and

show:function(value){
   // some code here
}
+1  A: 

One way of doing it:

var some_func = function(value) {  
    // some code here
}

Another way:

function some_funct() {
}

Yet another way:

var some_object={};
some_object["some_func"] = function() {};

or:

var some_object={};
some_object.some_func = function() {};

In other words, they are many ways to declare a function in JS.


Your second example is not correct.

jldupont
`some_object["some_func"] = function() {};` is cumbersome. Using dot notation is cleaner: `some_object.some_func = function() {};`
Justin Johnson
@Justin: ... and yet another way to declare a function!
jldupont
The declaration is the same (RHS), it's just the access notation that is different (LHS) ;)
Justin Johnson
@Justin: many thanks for adding precision to my contribution!
jldupont
@jldupont My pleasure.
Justin Johnson
+1  A: 

The first one is a function declaration assigned to a variable (at least it should be, despite the fact that it's missing the variable type declaration first), the second one is probably related to a object declaration.

yoda
Second form is sometimes used in object literals: `some_obj = {init: function() {},show: function() {}};`
MBO
updated the post, @senthil's answer is right as well.
yoda
+1  A: 

They are called anonymous functions; you can read more about them here:

http://www.ejball.com/EdAtWork/2005/03/28/JavaScriptAnonymousFunctions.aspx

Sarfraz
+3  A: 

First is local (or global) variable with assigned anonymous function.

var some_name = function(val) {};
some_name(42);

Second is property of some object (or function with label in front of it) with assigned anonymous function.

var obj = {
    show: function(val) {},
    // ...
};
obj.show(42);

Functions are first-class citizens in JavaScript, so you could assign them to variables and call those functions from variable.

You can even declare function with other name than variable which that function will be assigned to. It is handy when you want to define recursive methods, for example instead of this:

var obj = {
    show: function(val) {
        if (val > 0) { this.show(val-1); }
        print(val);
    }
};

you could write:

var obj = {
    show: function f(val) {
        if (val > 0) { f(val-1); }
        print(val);
    }
};
MBO
+7  A: 

The first one is simply creating an anonymous function and assigning it to a variable some_func. So using some_func() will call the function.

The second one should be part of an object notation

var obj = {
  show:function(value){
    // some code here
  }
};

So, obj.show() will call the function

In both cases, you are creating an anonymous function. But in the first case, you are simply assigning it to a variable. Whereas in the second case you are assigning it as a member of an object (possibly among many others).

Senthil
The outer parenthesis on `obj` are superfluous
Justin Johnson
Oh! A reply to one of my posts in SO about writing code using the module pattern said that without those parenthesis, sometimes anonymous functions might fail. I still didn't get an explanation as to why. Not sure whether they apply only to module patterns or all anonymous functions. That is why I added them.
Senthil
I think its only when you eval an object like `eval("({a:1})")`
S.Mark
I think @S.Mark is right. I've never seen the problem that you described in the other post. I wouldn't worry about it until it's actually a problem. Dev 1: "Why do we do abc?" Dev 2: "....because we've always done abc..."
Justin Johnson
Hmmm.. nice! :) I've edited the answer.
Senthil
The parentheses are necessary for functions that are invoked immediately, not object literals. A function declaration and a function expression are not the same thing, with the key point being that a function declaration cannot be invoked immediately. For example `(function() {})()` is a self-invoking function expression; the parentheses around `function(){}` are necessary to turn it into a function expression. Otherwise it is seen as a function declaration, on which the lack of an identifier (or, if an identifier is provided, the following `()`) would be a syntax error.
NickFitz
Hence it is applied in the module pattern where you evoke it after you declare it. Thanks for clearing that up! :)
Senthil
+1  A: 

The first example creates a global variable (if a local variable of that name doesn't already exist) called some_func, and assigns a function to it, so that some_func() may be invoked.

The second example is a function declaration inside an object. it assigns a function as the value of the show property of an object:

var myObj = {
    propString: "abc",
    propFunction: function() { alert('test'); }
};

myObj.propFunction();
David Hedlund
Your JSON notation is incorrect.
Justin Johnson
d'oh. thanks for noticing. if *that* would've been what i meant to write, i would not have addressed the actual question :D
David Hedlund
A: 

The first one...

some_func = function(value) {  
    // some code here
}

is declaring a variable and assigned an anonymous function to it, which is equivalent to...

function some_func (value) {  
    // some code here
}

The second one should look like this...

obj = {
    show:function(value){
       // some code here
    }
}
// obj.show(value)

and equivalent to...

//pseudo code
class MyClass {
    function show (value) {
        // some code here
    }
}
obj = new MyClass();    // obj.show(value)

Cheers

Ei Maung
Your last two examples are not equivalent since you cannot instantiate object literals (error: "TypeError: obj is not a constructor"). `var Obj = function() { this.show = function() {}; }` is equivalent to your pseudo code.
Justin Johnson
@Justin Johnson - Oh! Really? Then, why this work perfectly? `obj={show:function(value){alert("work");}} obj.show();`
Ei Maung
Yes really. I didn't say that `obj.show()` doesn't work, I said that your examples are not equivalent.
Justin Johnson
+2  A: 

There are five ways/contexts to in which to create functions:

1) Standard procedural notation (most familiar to people with C background)

function foo() {}

2) As a method of an object literal

var obj = {
    foo: function() {}
};

3) As a method of an instantiated object

var Obj = function() {
    this.foo = function() {};
};

4) As an anonymous function with a reference (same effect as #1) *

var foo = function() {};

5) As an immediately executed anonymous function (completely anonymous)

(function() {})();

* When I look at this statement, I consider the result. As such, I don't really consider these as anonymous, because a reference is immediately created to the function and is therefore no longer anonymous. But it's all the same to most people.

Justin Johnson