There are two main methods for creating JavaScript objects. The confusion arises in understanding when to use each notation. Below are examples of both literal and instance variables, each holding different values and producing different results when operated on.
In the environments I've worked in, the Literal notation is commonly used. However, as a .NET programmer, I see the 'new' keyword in JavaScript that resembles C#.
I currently work in a .NET shop and am exploring the world of WebForms.
So, the question is, why choose one over the other and does one work better with ASP.Net WebForms?
var instance1= new Menu1('Cheese', 'Onion');
var instance2 = new Menu1('Steak', 'Kidney');
var literal1 = Menu2;
literal1.Initialise('Fish', 'Chips')
var literal2 = Menu2;
literal2.Initialise('Sausage', 'Mash')
Literal - Original:
var Menu2 = {} | Menu2;
Menu2 =
{
//Properties
Item1 : '',
Item2 :'',
//Functions
Initialise: function(item1, item2)
{
Item1 = item1;
Item2 = item2;
},
GetItem : function(item)
{
switch(item)
{
case 'item1':
return Item1;
break;
case 'item2':
return Item2;
break;
}
}
}
Literal - EDIT:
var Menu2 =
{
//Properties
Item1 : '',
Item2 :'',
//Functions
Initialise: function(item1, item2)
{
this.Item1 = item1;
this.Item2 = item2;
},
GetItem : function(item)
{
switch(item)
{
case 'item1':
return this.Item1;
break;
case 'item2':
return this.Item2;
break;
}
}
}
Instance Notation
var Menu1 = function(item1, item2)
{
var _Item1 = item1;
var _Item2 = item2;
this.GetItem = function(item)
{
switch(item)
{
case 'item1':
return _Item1;
break;
case 'item2':
return _Item2;
break;
}
}
}
Thank you