Challenge with creating instances of a Javascript class

I'm currently delving into JavaScript OOP and have encountered an issue. While my code successfully works to change a class variable for a specific instance, it fails when I try to print the updated value in an event handler.

Initially setting "myname" with a default value, I later update it for a particular instance. However, when attempting to display the new value in the event handler, I still receive the default one instead.

Can anyone provide guidance on how to modify the code to address this issue?

Thank you!

function myClass () {}

myClass.prototype = 
{

    myname : "test",

    test  : function (filename)
    {
        var img = createSomething ();
        img.container = this;

        img.addEventListener('click', this.onClick);                    
    }, 


    onClick : function (e)
    {
        trace ("click: " + e.source.container.myname); // This will output "test" instead of the expected "dave"
    }

};



var instance = new myClass ();

instance.myname = "dave";

instance.test();

Answer №1

Although I am unfamiliar with trace() and e.source, when I implemented your code using console.log() and e.target.container.myname, it functioned flawlessly.

For reference: http://example.com/code-sample/

(please note that this example is optimized for browsers supporting addEventListener)

function customClass() {}

customClass.prototype = {
    
    myname: "trial",

    experiment: function(filename) {
        var picture = new Image();
        picture.src = "http://dummyimage.com/120x90/f00/fff.png&text=my+image";
        picture.container = this;

        picture.addEventListener('click', this.onSelect, false);
        document.body.appendChild(picture);
    },
    onSelect: function(e) {
        console.log("chosen: " + e.target.container.myname); 
    }
};
var testInstance = new customClass();
testInstance.myname = "sam";
testInstance.experiment();

UPDATE: Improved compatibility of addEventListener by including the recommended 3rd argument, as advised by @Jane Doe.

Answer №2

If you're looking to implement object-oriented programming (OOP), utilizing a bind function is essential. This method proves to be extremely beneficial when attaching event handlers that are specifically bound to your object rather than the global object.

function createBoundFunction(func, context) {
     return function() {
          return func.apply(context, Array.prototype.slice.call(arguments));
     }
}

Here is how you can apply this concept-

function CustomObject() {}

CustomObject.prototype = {

    name: "example",

    performAction: function(arg) {
        var element = document.createElement('div');
        element.innerText = arg;

        element.addEventListener('click', createBoundFunction(this.onClick, this), false);
        document.body.appendChild(element);
    },
    onClick: function(e) {
        // 'this' now refers to the instance of CustomObject
        console.log("Clicked: " + this.name); 
    }
};
var customInstance = new CustomObject();
customInstance.name = "Alice";
customInstance.performAction();

Note: It's common practice for constructor functions (or 'Classes') to begin with an uppercase letter.

Answer №3

Please be aware that this response may not directly address the question at hand.

If you're delving into OOP with Javascript, I highly suggest utilizing the Class class developed by the renowned John Resig. You can find more information about it here: http://ejohn.org/blog/simple-javascript-inheritance/

It truly streamlines the process of inheritance...

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

Which is the better choice for accessing and manipulating JSON files – using Ajax or the Node fs module?

When storing quiz questions using JSON data, should I use vanilla AJAX or Node.js file system to read the file? I am planning to develop a website where users can create quizzes and save them as JSON. I intend to utilize the Node.js fs module to save the ...

Transforming the output from a processor into an array structure

Being a newcomer in the field of development, I have a question about how to retrieve data based on my requirements and what is considered the best practice? This is the structure of my design: JavaScript (Ajax call) >> ashx handler (Access databa ...

javascript utilizing key inputs

Is there a way I can create a function that activates when the "A" key on my keyboard is pressed, sending a signal to nupp('/TS'), and stops sending the signal when the "A" key is released? <html> <head> <script src=\"htt ...

What could be causing variations in the performance of my Speech Recognition code each time I run it?

Check out my code snippet: export class voiceRecognition { constructor() { } public startVoiceRecognition() { const recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimresults = false; recogn ...

Why does the array format of the values saved in app.locals seem to disappear when they are accessed in the view?

I have created a date values array and stored it in an app.locals variable using the code snippet below: prepDataList.forEach(function(item){ var str = item.createdAtDate.toDateString(); //str = str.substring(4, 10); labelsArray.push(str); counts ...

Show a picture upon hovering the button

Welcome to my website. My goal: Show an image when a user hovers over the links. I must be making some silly error, but I can't pinpoint it. This is what I've attempted so far: HTML <ul class="nm"> <li><a href="#">Cork& ...

"Troubleshooting the issue of AngularJS $http patch request failing to send

The information is successfully logged in the console when passed to replyMessage, but for some reason, the API does not seem to be receiving the data. Is the input field perhaps empty? replyMessage: function(data) { console.log(data); ...

Utilizing Nicknames in a JavaScript Function

I'm dealing with a function that is responsible for constructing URLs using relative paths like ../../assets/images/content/recipe/. My goal is to replace the ../../assets/images section with a Vite alias, but I'm facing some challenges. Let me ...

Dynamic parallax effect with scroll wheel on WebKit

Currently experiencing some challenges with parallaxing backgrounds. I developed a website for an event organized by my friends, featuring multiple background images that shift between content sections to create a parallax effect. I have implemented code t ...

Struggling to map JSON data (received from WCFRest) onto an HTML table

After creating a WCFRestful service that populates data in JSON format as shown below: {"GetEmployeesJSONResult":"[{\"Name\":\"Sumanth\",\"Id\":101,\"Salary\":5000},{\"Name\":\"Sumanth\",\"I ...

Timeout set to run indefinitely

Looking at the code snippet below, it seems to be running at a frame rate of 60 frames per second. If any button is clicked, the variable isjump will be set to true and the following code will start executing. The goal here is to exit the jump() function a ...

What is the best way to keep a div element fixed on the page no matter where you scroll?

For example: I have an extensive inventory of items, and as I hover my mouse over each item, a corresponding picture appears in this section. The div stays fixed in place regardless of scrolling. It works similar to a frame. ...

Utilizing Google Tag Manager for Efficiently Managing Multiple Schema Product Reviews with JSON-LD and Variables

Currently, I am facing a challenge while using Google Tag Manager to incorporate Schema JSON-LD Product reviews on certain pages. Despite my efforts, I am unable to locate any relevant resources to resolve this issue. The main problem lies in informing GT ...

Position the vertical bar directly adjacent to the form input field

Looking for assistance with creating a unique webpage layout that includes a form where the employee ID is visually separated from the rest of the content by a vertical bar extending across the entire page. However, my attempts to achieve this using a gr ...

Remove array element by key (not numerical index but string key)

Here is a JavaScript array that I am working with: [#ad: Array[0]] #ad: Array[0] #image_upload: Array[0] 13b7afb8b11644e17569bd2efb571b10: "This is an error" 69553926a7783c27f7c18eff55cbd429: "Yet another error" ...

Trouble getting Fontawesome icons to accept color props when using react functional components with tailwindcss

Issue I'm Facing I'm currently working on a project that involves using icons extensively. Instead of manually adding a Fontawesome icon in every script, I have created a functional component that handles the rendering of icons based on given pr ...

npm fails during the build process due to webpack issues

I find myself lost in trying to pinpoint the right question to ask, but I am encountering a failure while running npm run build. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="395a5655564b14564b5e585750435c4b790817091709" ...

Is there a way for me to obtain the full error message after a failed fetch request?

I'm trying to capture all errors from the fetch function, including the specific red highlighted details as a string: https://i.sstatic.net/GtHxv.png But when I catch an error in my code, all I get is "Failed to fetch." Here's what my code looks ...

ShadowCamera is absent in Three.js

I'm currently exploring the world of Three.js and experimenting with this demo code: function init(){ var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, .1, 500); var renderer = new ...

Creating a legend in a pie chart with AmCharts: Easy steps to follow!

Here's a demo of my code: https://jsfiddle.net/oscar11/4qdan7k7/6/ This is the code snippet I am using: "legend": { "useGraphSettings": true } Unfortunately, it's not working as expected. The result looks like this: https://i.sstatic.net/q ...