简体   繁体   中英

Literal and Instance Notations in Javascript

I know that there are two main methods of instantiating JavaScript objects.

Where I get confused is where the two types of notations come into their own.

Taking the below samples. Both the instance variables and the literal variables hold different values and both operations on each variable will return a different result.

I have always worked in environments where the Literal notation is used exclusively, however as a .NET programmer I recognise the new keyword and think it makes JavaScript look a little more like c#.

I work in a .NET shop and am currently playing in the WebForms world.

My question is, why would you use one over the other and does one play 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;      
    }       
}   
}

Thanks

It is simple. You would use the Instance notation if you want your objects to have a specific type and eventually to have some kind of hierarchy. For example:

function Dog(){};

var dog = new Dog();
var dog1 = {};

dog instanceof Dog //true
dog1 instanceof Dog //false

The other usage is for cases when you do not want to return specific types but a simple objects from which you will need certain properties.

In simple words, the first notation gives you some OOP which is just a little bit like in languages such as C#. EcmaScript6 Classes get a tiny bit closer to this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM