Utilizing Literal and Instance Formats in JavaScript

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

Answer №1

Using the Instance notation is beneficial when you want your objects to adhere to a specific type and potentially form a hierarchy. For instance:

function Cat(){};

var cat = new Cat();
var cat1 = {};

cat instanceof Cat //true
cat1 instanceof Cat //false

On the other hand, this notation is useful when you simply need to return objects with specific properties, regardless of their type.

In essence, the first method provides a level of object-oriented programming similar to languages like C#. EcmaScript6 Classes are getting closer to this concept.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you use JavaScript to create a JSON object using values from an HTML form textarea and then send

I need to create an HTML form that will send specific information in the Http-request body. { “info” : { “id” : “123” “text1” : <data from html text-box> } Therefore, my goal is to convert the provided data into a JavaScri ...

Executing a function while adjusting a range slider

Having an <input type="range"> element on my website presents a particular challenge. To handle changes in this element, I am using the following function: $("#selector").bind("change", function() { //perform desire ...

Step-by-step guide on adding an ASP button that will show additional textboxes when activated

My goal is to allow users to add more information to a webform by clicking a button to reveal an additional text box. Currently, I have 3 textboxes and buttons in my implementation with only the first one visible. The idea is to track which textbox should ...

Executing PHP include statement with ajax: A step-by-step guide

I am trying to achieve a feature on my website where when a button is clicked in the index.php file, an AJAX request will load about.php and display it inside a div tag within index.php. Unfortunately, my current code doesn't seem to be working as exp ...

How can a 'complete' event listener be executed for a custom function in JQuery/JavaScript?

Here is the code snippet I'm working with: $('.fblikes span').fblikecount(); $.fn.fblikecount = function(){ //Perform JSON XHR operations to retrieve FB like counts and update the page numbers } This code will cycle through all insta ...

MongoDB Stitch retrieves all data fields

Can anyone help me with my MongoDB query issue? I've recently started working with mongoDB and I'm having trouble getting just one field back for all my documents. var docs = db.collection("articles").find({}, { _id: 0, title:1}).asArray(); De ...

Disappearing Data in Chart.js When Window is Resized

I am utilizing the Chart.js library to present a line chart in a div that is enclosed within a <tr>. <tr class="item">...</tr> <tr class="item-details"> ... <div class="col-sm-6 col-xs-12 chart-pane"> <div clas ...

Designing an interactive 3D space using JavaScript

I'm currently developing an app that allows users to visualize different wallpapers in a 3D room setting. The concept involves placing the user inside a virtual space with four walls, where they can drag and look around, as well as change wallpapers v ...

What could be causing my jQuery switch not to function on the second page of a table in my Laravel project?

Having an issue with a button that is supposed to change the status value of a db column. It seems to only work for the first 10 rows in the table and stops functioning on the 2nd page. I'm new and could really use some help with this. Here's the ...

What are the capabilities of an INNER JOIN query in Objection JS?

Here is the data model that I am working with: https://i.stack.imgur.com/g1T5i.jpg In this model, a User can be associated with multiple Projects, and a Project can have many Users. These relationships are managed through a join table called UserProjects. ...

How to customize the button color in a Next.js application

Help Needed: Issue with Changing Default Button Color in Next.JS Web Application. The button text color appears as grey on Desktop Google Chrome, but shows up as blue on Mobile Chrome browser. I want to unify the color to be grey on both platforms. Custo ...

Ways to retrieve all elements based on their class names?

What is the equivalent of using $('.class') in JQuery to get all elements by class name with pure JavaScript? ...

When utilizing a Slick carousel with three slides and setting autoPlay to true, the slider-nav behaves as if there are five slides

I am currently using the Slick carousel plugin and I want to feature a display of 3 photos. The issue is that when I set slidesToShow=2, everything works perfectly fine, but when I try to set slidesToShow=3, which equals the total number of slides, the bot ...

Is there a way to horizontally center Material UI Switch and its icon props?

I'm using Material-UI to implement a Switch component on my project. This particular component allows for the addition of icons, however, I've encountered an issue with alignment when including them. Is there a way to horizontally center align b ...

JavaScript table supported by a REST API

Issue at hand: I am in search of a table component that seamlessly integrates with my web application. The challenge lies in connecting the existing REST endpoints to the table for data retrieval, whether it be paginated or not. Adjusting the endpoints t ...

Incorporating additional options onto the menu

I recently designed a menu on https://codepen.io/ettrics/pen/ZYqKGb with 5 unique menu titles. However, I now have the need to add a sixth title to the menu. After attempting to do so by adding "strip6" in my CSS, the menu ended up malfunctioning and looki ...

The setInterval function does not function properly in IE8 when set to 0

I have a function called changeColor that updates the styling of certain elements in my HTML. In order to apply this function, I am using a timer like so: var timer = setInterval(changeColor,0); The issue I am encountering is that setting the time interv ...

Utilize morris.js within an AngularJS directive to handle undefined data

Using the morris.js charts in my angular js app has been a great addition. I decided to convert it into a directive for better organization and functionality: barchart.js: angular.module('app_name').directive('barchart', function () ...

Guide to summing the values in an input box with TypeScript

https://i.stack.imgur.com/ezzVQ.png I am trying to calculate the total value of apple, orange, and mango and display it. Below is the code I have attempted: <div class="row col-12 " ngModelGroup="cntMap"> <div class="form-group col-6"> ...

Animating with JavaScript

I have a members button on my website that triggers a dropdown animation when clicked. However, the issue is that the animation occurs every time a page is loaded, even if the button is not clicked. I want the dropdown to only open when the button is click ...