theHack
theHack

Reputation: 2014

javascript create function

What is the difference between this:

var doSomething=function()
{
    //do blah blah blah...  
}

And this:

function doSomething()
{
    //do blah blah blah...  
}

Another question: In PHP, we create a function by doing this:

function doSomething(a,b)
{
    //do something to variable a and b...
}

In JavaScript, we may have an object before the function:

object.doSomething(a);

My second question is, how would you create a function which requires an object in JavaScript?

Upvotes: 3

Views: 16274

Answers (4)

Aleksi Yrttiaho
Aleksi Yrttiaho

Reputation: 8446

The difference between var fun = function() {} and function fun() {} is that in the first case it is stored in the variable fun. To call the function, you have to call fun(). Having it in a variable lets you pass the function around.

You can create objects by using functions

function MyClass() {
    this.fun = function() { alert('Hello world'); }
}

var obj = new MyClass();
obj.fun();

or JSON

var obj = {
   fun: function() { alert('Hello world'); }
};

obj.fun();

You can further extend the objects or their prototypes with new functions.

Edit. Sorry for the wrong answer: one shouldn't try to do these kinds of things at 4 am.

Upvotes: 1

Wayne
Wayne

Reputation: 60414

The number one Google result for "function statement vs expression javascript" is another Stack Overflow question:

What is the difference between a function expression vs declaration in JavaScript?

It references the following article, which is the definitive reference on the subject:

http://kangax.github.com/nfe/

Upvotes: 6

Ken Wayne VanderLinde
Ken Wayne VanderLinde

Reputation: 19349

For the second part of the question, we just do something like

object.doSomething = function(a) { ... }

which is one reason the function literal is so useful.

Upvotes: 0

Jeff
Jeff

Reputation: 4146

One question at a time.

To answer your first question, there is not a huge difference.

function doSomething() {} 

is technically equivalent to:

var doSomething;
doSomething = function() {};

technically what happens in this case is the variable declaration gets hoisted to the top of your script.

Upvotes: 0

Related Questions