Instantiate an object within a jQuery click event

Hey there! I have been experimenting with some oojs, attempting to complete a very simple test.

If you want to take a look at the code, check it out here: view the test jsbin

I realized that I struggled to create a new instance of an object inside a function without either moving it outside the function or using window.person.

window.person = new person();

I have a suspicion that this might be incorrect.

My question is, is there a more effective approach to achieve this, and is utilizing window.person a poor choice for creating a new instance?

Answer №1

The problem lies in the fact that your new instance of Person is overwriting the constructor.

By defining a function outside of a scope, you are essentially attaching it to the window object (the "global" scope). This means that your function Person becomes window.Person.

Within your click event, you are re-assigning window.Person with

window.Person = new Person(clicked);

To resolve this issue, you could simply rename your window.Person variable created in the click callback. A better solution would be to utilize closures. This will help maintain a cleaner window scope and address the problem effectively.

When naming variables and constructors, it's commonly recommended to follow these guidelines:

  • Constructor function names should start with an uppercase letter (e.g., function Person)
  • Normal variables should start with a lowercase letter (e.g., var person)

This practice helps prevent confusion when using syntax like var person = new Person().

The revised code would look like this:

function Person(name){
    this.name = name;
    this.alert = function(){
        alert("hello " + this.name);
    };
}

function Area (location, name){
    this.name = name;
    this.location = location;
    this.alert = function(){
        alert("hello " + this.name + " you live in " + this.location);
    };
}

$(document).ready(function(){
    var person;
    $(".button").click(function(){
        var clicked = $(this).text();
        person = new Person(clicked);
        person.alert();  
    });

    $(".button2").click(function(){
        var location = $(this).text();
        var name =  person.name;
        var area = new Area(location, name);
        area.alert();  
    });
});

If you need to access the area variable outside of the click function, you can also consider moving var area directly under the declaration of var person.

Answer №2

Simply place the instance in the outer scope:

let user, areaSelected;

$(document).ready(function(){

    $(".button").click(function(){
        let clickedButton = $(this).text();
        user = new User(clickedButton);
        user.display();  
    });

    $(".button2").click(function(){
        let selectedLocation = $(this).text();
        let userName =  user.name;
        areaSelected = new SelectedArea(selectedLocation, userName);
        areaSelected.display(); 
    });

});

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

Laravel - AutoComplete Feature: Populate Input Field with JSON Data Instead of Suggestions

I've been working on adding search functionality to my Laravel 5.4 project, but I'm running into an issue. The suggestions show up fine in the dropdown menu, but when I select one, the input field gets filled with JSON data instead of the suggest ...

Adjusting image dynamically based on conditions

I need to dynamically display images on my HTML based on specific conditions using TypeScript. In my TypeScript file: styleArray = ["Solitary", "Visual","Auditory","Logical","Physical","Social","Verbal",]; constructor(){ for (var i = 0; this.sty ...

Fill in according to the options selected in the dropdown menu

Recently delving into the world of React, I encountered a design challenge that needs solving. My goal is to have a selection field with various choice values, each offering different sets of KPIs and UOMs. Depending on the chosen value, I should be able t ...

Transferring Variables to the Following Page Without Using a Form or Changing the URL

I have a question about passing a variable along with a link to exampleA.php without using URL extensions or form submitting. I've done some research and found that most people suggest using Ajax, but I want to handle the variable once I'm on the ...

Displaying a popover upon page load using JavaScript

Currently, I am attempting to implement a JavaScript function that displays a popup on my webpage whenever a user visits the site. The script that I have found uses jQuery, but I am wondering if it is possible to achieve the same result using pure JavaScri ...

Javascript Error: Object Expected

Recently, I have encountered an error in my code that says "object expected" in JavaScript. Surprisingly, the code was working perfectly fine before this issue arose. Strangely, the code is still functioning properly in another solution. Even after making ...

extracting information from an external document

I'm quite new to both three.js and JavaScript, so please bear with me if this is a simple question. I have a JSON file with a list of objects containing data like this: [ { "x":x,"y":y,"z":z ,"r":r}, { "x":x2,"y":y2,"z":z2 ,"r":r2}, { "x":x3,"y":y3, ...

Tips for retrieving the checked status of a Material UI <Checkbox/> component and changing it to false upon clicking a different icon (such as a delete icon)

Greetings! I have encountered a problem that I am hoping someone can assist me with. I am looking for information or guidance on how to handle a specific issue. The challenge I am facing involves accessing the checked property of a material-ui <Checkbo ...

The Highchart data series seems to be getting cut off

Can anyone assist me in creating a 24-hour data chart using Highcharts? I am encountering an issue where the first two data points are not rendering correctly, showing 11 columns instead of 12. I have provided an example here. Any help would be greatly a ...

Incorporate dynamic variables into your HTML code using jQuery or JavaScript

I'm struggling to generate HTML code from JavaScript/jQuery within an HTML template rendered in Django. I need to append HTML code and also insert some values in between. Currently, I am using a basic string append method like this: var features =[&ap ...

Adjust the transparency of a separate image within a different container by hovering over another image container

Is my goal too complex to achieve? I am attempting to create a hover effect where the opacity of artwork1 and button1 changes simultaneously when hovered over. However, I am having trouble properly labeling my elements and getting them to interact as inten ...

Executing JavaScript functions within static files in Django

I can't figure out why I'm unable to invoke a javascript function when clicking my Bootstrap button in a Django project. In my directory, I have set up the static folder as "main/static/main/js/script.js". While I can successfully load the stati ...

Adjust the child element's value by referencing the parent class name

I need to update the content of child elements within an HTML file based on the class name of their parent element, using JavaScript. While I have successfully achieved this for static values by creating a TreeWalker for text nodes, doing the same for dyn ...

Tick the checkbox if the Angular function evaluates to true

I'm facing a challenge with checkboxes related to available cars and determining whether they need to be checked based on the user's rented cars. Essentially, I have an array of all available cars named $scope.cars, and each user has an array ca ...

Tips for handling TypeError when testing formgroups in Angular unit tests---How to address TypeError

While attempting to conduct unit testing on my form fields in Angular, I encountered an issue with Karma stating that my property is undefined. When I logged the formGroup, it returned as undefined. However, upon logging my component, all parameters were r ...

Highcharts does not display the error message: "undefined is not a function"

I attempted to execute a sample code from this source, however, it failed to display. The error message in my browser's console points to the line: <script type="text/javascript"> $(function () { $('#container').highcharts ...

Obtain data from files within a React frontend application

I have integrated an API endpoint into my NodeJS application. The purpose of this endpoint is to locate a specific file in a folder based on the filename provided in the request. Here's how I am approaching this: const fileDirectory = 'C:/Sites/p ...

Displaying a div on click using Jquery will only impact one div at a time

I am encountering an issue with my WordPress setup. Within my loop, I have a clickable link that toggles a div to show or hide content. However, since each item in the loop uses the same class, clicking on one link activates all of them simultaneously. &l ...

When the route is modified, the image fetched from the JSON disappears

When using a div tag to display JSON values on an image, I noticed that the values disappear when navigating to other pages and then returning to the home page. This issue is occurring as I develop with Angular.js NumberJson.get().then(function (resul ...

Issue encountered with my AJAX request in JavaScript on Internet Explorer 8

Check out the range of products available on this website using jQuery When using Firefox or Safari, clicking on view will show you more product details on the right side. This could include a gallery with multiple images, downloadable spec sheets if av ...