liorafar
liorafar

Reputation: 2364

Misunderstanding in Javascript statements

I've just started working with javascript and I saw something which I can't explain.
I have js file named TestClass.js and its the following:

TestClass.SetError = function (errorDescription, errorCode, typedErrorCode)
{
    alert("SetError ");
}  

function SetError2(errorCode)
{
    alert("SetError2 ");
}  

Can someone please explain me the difference between the SetError and SetError2?

Upvotes: 2

Views: 97

Answers (6)

Dmitry Pashkevich
Dmitry Pashkevich

Reputation: 13546

The first piece of code (SetError) contains Anonymous Function Expression, where the second piece of code (SetError2) cotains a Function Declaration. See Function Declarations vs. Function Expressions

Another good article: Named function expressions demystified

Excerpt:

function declarations are parsed and evaluated before any other expressions are. Even if declaration is positioned last in a source, it will be evaluated foremost any other expressions contained in a scope.

That's basically the main difference. It's not huge but worth being aware of.

Upvotes: 1

Reza Owliaei
Reza Owliaei

Reputation: 3373

Javascript has Objects and Functions.

An Object can contains Objects and/or functions.

this is an object:

var TestClass = {};

you can add a new object to TestClass Object as following:

var TestClass = { object : {}};

Then you can have an access to it like this:

var a = TestClass.object;

You can have a function in an object:

var TestClass = {object:{}, setError:function(){/*function body*/}};

Now you can invoke the function of test class like this:

TestClass.setError();

In addition, Function itself can be defined like this:

function setError2(){/*function body*/}

and you may invoke like this:

setError2();

usually, we define functions in objects to somehow implement OO in Javascript and prevent messy js codes.

Upvotes: 0

AboQutiesh
AboQutiesh

Reputation: 1716

the difference lies in how the browser loads them into the execution context.

function loads before any code is executed.

While expressions loads only when the interpreter reaches that line of code.

Upvotes: 1

troelskn
troelskn

Reputation: 117615

This:

function SetError2(errorCode) {
  alert("SetError2 ");
}

Is equivalent to this:

window.SetError2 = function(errorCode) {
  alert("SetError2 ");
}

Upvotes: -2

Lews Therin
Lews Therin

Reputation: 10995

SetError2 is a "named" method. TestClass.SetError is a member variable of TestClass that references an anonymous method. Which means later you can do TestClass.SetError = function(){ alert ("SetError2");}

Upvotes: 0

user1028286
user1028286

Reputation:

SetError is a method of the object TestClass. Whereas SetError2 is a global function.

Upvotes: 1

Related Questions