JavaScript function declaration
Asked Answered
O

8

27

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
}
Outstanding answered 8/12, 2009 at 10:32 Comment(0)
P
25

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

Potboy answered 8/12, 2009 at 10:37 Comment(6)
The outer parenthesis on obj are superfluousAnabelle
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.Potboy
I think its only when you eval an object like eval("({a:1})")Osi
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..."Anabelle
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.Phenacite
Hence it is applied in the module pattern where you evoke it after you declare it. Thanks for clearing that up! :)Potboy
A
72

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

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

function foo() {}

All the rest are function expressions:

2) As a method of an object literal

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

3) As a method of an instantiated object (created each time new is exectued)

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

4) As a method of a prototype (created only once, regardless of how many times new is executed)

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

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

var foo = function() {};

6) 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.

Anabelle answered 8/12, 2009 at 10:55 Comment(3)
Is there a reason to prefer #1 or #5? I see #5 in a lot of libaries, and occasionally #1.Coadjutress
Never mind, I found the answer myself here: javascriptweblog.wordpress.com/2010/07/06/…Coadjutress
It is misleading to suggest #1 and #5 are effectively the same, they are very different. As well as the link provided by EsTeGe, also check the excellent answer to this SO question which explains very well the difference: #3887908Lissome
P
25

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

Potboy answered 8/12, 2009 at 10:37 Comment(6)
The outer parenthesis on obj are superfluousAnabelle
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.Potboy
I think its only when you eval an object like eval("({a:1})")Osi
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..."Anabelle
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.Phenacite
Hence it is applied in the module pattern where you evoke it after you declare it. Thanks for clearing that up! :)Potboy
I
4

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);
    }
};
Income answered 8/12, 2009 at 10:36 Comment(0)
L
2

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.

Lucilla answered 8/12, 2009 at 10:35 Comment(4)
some_object["some_func"] = function() {}; is cumbersome. Using dot notation is cleaner: some_object.some_func = function() {};Anabelle
@Justin: ... and yet another way to declare a function!Lucilla
The declaration is the same (RHS), it's just the access notation that is different (LHS) ;)Anabelle
@Justin: many thanks for adding precision to my contribution!Lucilla
L
1

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.

Lohman answered 8/12, 2009 at 10:35 Comment(1)
Second form is sometimes used in object literals: some_obj = { init: function() {}, show: function() {} };Income
N
1

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

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

Nidify answered 8/12, 2009 at 10:36 Comment(0)
P
1

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();
Package answered 8/12, 2009 at 10:38 Comment(1)
d'oh. thanks for noticing. if that would've been what i meant to write, i would not have addressed the actual question :DPackage
T
0

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

Tound answered 8/12, 2009 at 10:46 Comment(3)
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.Anabelle
@Justin Johnson - Oh! Really? Then, why this work perfectly? obj={show:function(value){alert("work");}} obj.show();Tound
Yes really. I didn't say that obj.show() doesn't work, I said that your examples are not equivalent.Anabelle

© 2022 - 2024 — McMap. All rights reserved.