What is the difference between declaring javascript objects with var and function?

I am a confused newbie. I read in a tutorial that you create a javascript object as follows:

function myObject() { this.myProperty = "a string"; this.myMethod = function () { //Method code } } 

Then I read somewhere else that you are creating an object like this:

 var myObject = { myProperty: "a string", myMethod : function () { //Method code } } 

What is the (non-subjective) difference between the two? Is there a right way and a wrong way?

+7
javascript function object oop var
source share
3 answers

Both declarations are correct, but have different semantics.

The first type of declaration allows you to instantiate your objects:

 var t = new myObject(); // then use t t.myProperty = "some value"; var otherT = new myObject(); otherT.myProperty = "some other value"; 

The second is almost like a static object:

 myObject.myProperty = "some value"; 
+5
source share

Here is a direct comparison ...

 function myObject() { 

This declares a function when parsing JavaScript ...

 var myObject = function () { 

This declares a function at runtime.

If you use the var method, your function must be declared before using it ... try this example.

 myFunction(); // Works myVarFunction(); // Boom var myVarFunction = function () { alert("Hi"); }; function myFunction() { alert("Hi"); }; 

So why use the "var" method if you need to be more careful to use it? It all depends on the scope ... features with advanced features are considered the best.

UPDATE: And here are some great explanations:

var functionName = function () {} vs function functionName () {}

+3
source share

The main difference between the two is that one variable is local and the other global. "var" basically defines the scope of the variable.

When we add var to the value assignment of a variable, javascript ensures that the variable is limited to the function to which it is assigned and does not collide with the same variable in another function.

When we do not use var, then it is declared a global function, and the likelihood of a collision can occur. Therefore, it is always recommended to use "var" before assigning a value to a variable. If necessary, use an anonymous function to close.

0
source share

All Articles