Retrieving variables from a function within a structured framework

I am attempting to create a custom "struct" and utilize it in a similar way as I would in another programming language such as Swift. Below is the definition of the "struct":

var myStruct = function (prop1) {
    this.prop1 = 30;
}

My attempt to access prop1 looks like this:

var someVar = myStruct.prop1

Unfortunately, this approach does not seem to be working. Can someone please point out what mistake I might be making and suggest a solution?

For reference, here is the link to the JSFiddle, containing the complete code:

$(document).ready(function(){
    var myStruct = function (prop1) {
this.prop1 = 30;
}
    
    $("button").click(function(){
       $("p").css({"width": myStruct.prop1, "font-size": "200%"});
    });
});
<body>

<h2>This is a heading</h2>

<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>

<p>This is a paragraph.</p>

<button>Set multiple styles for p</button>

Answer №1

If you want to utilize a constructor for generating the instances, follow this syntax:

function MyCustomClass(parameter) {
    this.parameter = parameter;
}

To create an instance of that class, do the following:

var newObj = new MyCustomClass(40);

To access the property of the created instance, use the code snippet below:

console.log(newObj.parameter);

After passing in the value 40 to the object, the property this.parameter will be set to 40 and this value will be printed in the console log.

A big thank you to @Tiny_Giant for providing additional details on this topic.

Answer №2

What you have created is known as an Object Constructor. In order to obtain an object from the constructor, you would utilize the new keyword to generate a new instance of the object. However, it is advisable not to use this method unless multiple instances of the object are required.

$(document).ready(function(){
    var myStruct = function () {
        this.prop1 = 30;
    }

    $("button").click(function(){
        $("p").css({"width": new myStruct().prop1, "font-size": "200%"});
    });
});

If creating separate instances of the object is unnecessary, you can construct a new Object using the syntax exemplified in the following example.

Take note:

  • This syntax permits access to the properties similar to what was attempted in your sample code.
  • The syntax employed in the example below already involves passing an object to the $('p').css() method.
  • When utilizing this syntax, properties should be delimited by commas instead of semicolons, mirroring how arrays are used.
  • For any object property with special characters in its name, enclose it in quotation marks and access it through the object["property"] notation.

$(document).ready(function(){
    var myStruct = {
        width: '30px',
        fontsize: '200%'
    }
    
    $("button").click(function(){
       $("p").css({
            "width": myStruct.width, 
            "font-size": myStruct.fontsize
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>

<h2>This is a heading</h2>

<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>

<p>This is a paragraph.</p>

<button>Set multiple styles for p</button>

Answer №3

The following code snippet showcases how to declare a class:

var myClass = function (property) {
    this.property = 50;
}

Here is an example of how the class is implemented:

var objectInstance = new myClass(2);

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

Using JQuery and CSS to handle multiple hyperlink links with a single action

UPDATE: Issue resolved, thanks for the help. It is working fine now: http://jsfiddle.net/c3AeN/1/ by Sudharsan I have multiple links on my webpage, all in a similar format like this: note: When I say 'similar format', I mean that all links share ...

What could be causing my <UL> to not properly expand around the <LI> items inside of it?

I am currently working with WordPress and have created a menu using a list structure. Here is an example of how it looks: <ul> <li>Home</li> <li>About</li> <li>ParentItem <ul> <--- The heig ...

Tips for stopping html form from refreshing upon submission

Hello, despite extensive searching and testing, I am still unable to locate the issue and therefore I am reaching out to seek your assistance in resolving my problem. Within a form that I have created, upon clicking the submit button, a javascript functio ...

Shader in THREE.js only appears when the window is resized

I recently started working with THREE.js and have been experimenting with shaders. Strangely, I've noticed that this particular shader only displays correctly when I resize the window. You can find the code here. Any ideas on why it's behaving th ...

Sorting tables using jQuery when receiving tables via AJAX requests

I have developed a custom script that enables me to search torrent sites. When the page loads, there is a text area on the left for entering search queries and an empty div on the right. The search functionality utilizes AJAX to fetch search results in the ...

The React snackbar is mysteriously peeking out from behind the popup

While using the react-notifications-component snack bar, I encountered an issue where my snack bar was appearing behind the pop-up. Is there a way to fix this with z-index? I tried using <ReactNotification style={{ zIndex: 10000 }}/>, but it didn&ap ...

Is it better to patiently await an AJAX request within a function using $.Deferred, $.When, or jQuery?

How can I ensure that a deferred function waits until an AJAX call is completed? Here's an example: function action() { console.log('action has been initiated'); var deferred = $.Deferred(); ...

Hilarious rendering glitch with CSS in IE where the background image inexplicably contains the style "display: block."

Encountering a curious issue with how IE is interpreting my css. The defined style includes "background-image: url(/images/leftArrow.png); DISPLAY: block; cursor: pointer;" However, IE 7 & 8 seem to be merging background and display as one property (r ...

JavaScript and CSOM updates cause SharePoint list item properties to disappear

Within my SharePoint environment, there exists a website where users can load a single list item based on their selection using JavaScript and CSOM. This particular list item contains approximately 60 properties defined in its list definition. Users have ...

jQuery fadeOut and fadeIn functions not functioning properly in Internet Explorer

Looking for some assistance with a website issue I'm experiencing. My site includes a div containing content and a navbar resembling three tabs. JQuery is incorporated on the page to enable specific functionality: when a tab is clicked, the entire div ...

Looking for assistance with my website's navigation bar and logo

Looking for assistance in moving my navigation buttons to each side of the logo. As a beginner in web design and CSS, I've been struggling with this task. Essentially, I want the "home" and "about" buttons on the left side of the logo, 16px apart from ...

Enhance the current model in backbone.js by incorporating additional data

When a user selects an item on the webpage, more details need to be fetched and displayed. The API function /api/full_details has been implemented to return the additional data for that item. Challenge: How can I retrieve the additional data and append it ...

Enforce a limit of two decimal places on input fields using jQuery

Looking to limit an input field so that users can only enter numbers with a maximum of two decimals. Is it possible to achieve this using jQuery? Any way I could utilize the jQuery toFixed() function for this purpose? Thank you in advance! ...

HTML filtering using the <select> element

Is there a way to implement this script for options instead of buttons? The goal is to filter the HTML section, but it seems to not work with <option> tags. Instead of displaying the all class, it shows nothing. CSS .show { display: block; } .filt ...

Discovering the process of retrieving API data upon a button click within Next.js using server-side rendering

Hi there, I'm fairly new to working with next.js and would greatly appreciate some assistance. I am trying to figure out how to fetch data from an API upon clicking a button in next.js on the server side. I understand that using onClick directly is ...

What is the best way to implement a media query for changing styles on hover for an element

I am facing an issue with media queries where when I apply a hover effect to an element, such as a clickable link in the navigation bar, the new rules work as expected but also retain the default browser styles. For instance: nav ul li a:hover{ border:0; ...

Tips for creating a unique custom rounded underline effect in an Angular Material Tab

Our design team has requested that we incorporate underlines that resemble the top half of a rectangle with rounded corners. We are currently using Angular Material, but I am facing difficulties in styling the existing tabs component (https://material.angu ...

"Retrieving Data Using jQuery's .ajax Method in Visual Basic

<WebMethod()> Public Shared Function gtet() As String ... Dim GET = uClass.GetSets(dbuser, dbparam1) ... End Function and $(document).ready(function () { data = { }; var jsondata = $.toJSON(data); $.ajax({ type: "GET ...

The map on my leaflet only loads the initial row of tiles

I'm having trouble loading Leaflet map tiles beyond the first row in my Vue 3 component. I've experimented with various ways to declare the vertical size of the div, and have attempted to use map.invalidateSize() on mount, but so far no luck. < ...

Fetch solely the metadata from HTML5 video and audio files

Before we dive in, let me address a question I have regarding video metadata loading without any additional video content. The preload = "metadata" attribute doesn't seem to be functioning as expected. My testing thus far has been limited to Win Chrom ...