What is causing the Uncaught TypeError when invoking a private JavaScript ES5 class?

My goal is to create a JavaScript class using ES5 syntax. However, I encountered an error when calling one method from another, which displays the following message in the console:

Uncaught TypeError: root.abLog is not a function

The relevant code snippet causing the issue is as follows:

var abClass = function(options) {

    var root = this;

    this.checkAttach = function(text){
        root.abLog('Checking attached');
        /* snip */
    };

    var abLog = function(data) {
        console.log('abClass PATH: "'+vars.path+'"');
        console.log('abClass: '+data);
    };

};

Both root.abLog('Checking attached'); and this.abLog('Checking attached'); lead to similar errors being thrown.

I'm unsure of what mistake I've made with what I believe is a private method implementation. Can you help me identify and correct it?

Answer №1

When calling the function, omit using root or this like this -

var abClass = function(options){

   var root = this;

   this.checkAttach = function(text){
       abLog('Checking attached');
       /* snip */
   };

   var abLog = function(data) {
       console.log('abClass PATH: "'+vars.path+'"');
       console.log('abClass: '+data);
   };

};

The function abLog is a private function within your abClass, and the scope of this (attached to root in this case) receives a copy of public members of the class, which are directly attached via this.XXX. In this scenario, only checkAttach is attached to this, making it a public member.

For experimentation and debugging, check out this JS bin.

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

Avoid prompting unsaved changes notification when running OnSelectedIndexChanged event for a drop-down list

Incorporating this jQuery code to detect unsaved modifications and notify users before they navigate away has been really helpful. var _changesMade = false; $(document).ready(function () { $('form').bind($.browser.msie ? 'p ...

Tips for launching a PDF using Javascript

I have been working on developing an application that generates PDF files server-side. I am using AJAX for polling a server-side handler and retrieving it once the generation is complete. As I near completion, I encountered a problem where the entire PDF ...

Utilizing multiple physics simulations in Node.js, failing to optimize server efficiency

My multiplayer game worlds are hosted on AWS using Node and are physics-based (using p2.js), with a physics step rate of 200 steps per second. Each game has its own world and needs to step every 5ms. With only 6-8 players in each game, I can currently hos ...

What is the best way to retrieve an array situated inside an array of objects in Angular?

My dataset consists of an array of object entries for employees, structured as shown below: [ { id: "1", name: "name", email: "email", languages: ['english', 'german', 'spanish'] }, { ...

select specific region within image

I'm currently working on cropping an image and sending the cropped data to the server side. To achieve this, I am utilizing the imgareaselect plugin. While I am able to obtain the coordinates of the selection, I am facing challenges in actually croppi ...

Activate the download upon clicking in Angular 2

One situation is the following where an icon has a click event <md-list-item *ngFor="let history of exportHistory"> <md-icon (click)="onDownloadClick(history)" md-list-avatar>file_download</md-icon> <a md-line> ...

What causes the inconsistency in time intervals in the loop?

My goal was to create a simple slider that loops through 3 images, with each image staying visible for 3 seconds before fading out and the next one fading in. However, I encountered an issue: The first image can stay for 3 seconds, but once the loop star ...

Chai encountering issue with async/await when parameter is not provided

When testing my Typescript code, I encountered an issue where it should throw an error when no parameter is passed. getID(ID) { if(!ID){throw new Error('stop js')} ....} it('should fail if no ID', async () => { expect(async ( ...

If the given response `resp` can be parsed as JSON, then the function `$

I was using this script to check if the server's response data is in JSON format: try { json = $.parseJSON(resp); } catch (error) { json = null; } if (json) { // } else { // } However, I noticed that it returns true when 'res ...

What is the best way to verify the relationship between parent and children nodes in a tree structure?

Check out my Plnkr with nested loops of checkboxes: here Below is the HTML code for the nested loops of checkboxes: <ul> <li ng-repeat="continent in destinations"> <input type="checkbox" ng-model="continent.selected"> {{contin ...

iOS experiences a lag in loading dynamic images

I have created a unique jquery carousel specifically designed for mobile devices. It features three containers that display three images at a time, with jquery handling the animation. By detecting the user's swipe direction (left or right), I update t ...

Send the output of MPDF back to the browser by utilizing JSON in combination with ExtJS

I am currently using mpdf to generate a PDF report in my PHP code. I have successfully been able to save the PDF file and view it by using Output($pdfFilePath), but now I need to send it back to the browser using JSON without saving it on the server. To ac ...

Error: Property cannot be read after page refresh or modification

Upon refreshing or running the project for the first time, I encounter the error: TypeError: Cannot read property 'statements' of undefined This issue is perplexing as the data renders correctly but it appears that the connection is failing. ...

Stretching the limits: Combining and expanding your Styled Components theme

I am facing a situation where I have a component library built using Styled Components that has its own theme settings which are not meant to be overridden. Now, I need to incorporate this component library into another project that also uses Style Compone ...

Stop objects from shifting while easily applying a border

I have a code that adds a red border around elements when you mouseover them and removes it when you mouseout. However, the elements jump around when the border is added because it changes their dimensions. Is there a way to stop this jumping behavior? ...

Could this be a substance made of pure white energy?

It appears that the default color for SpriteMaterial is 0xFFFFFF, which indicates no color. However, if I change the color property of the material to say 0xFF0000, the sprite will display a red tint. If I desire a white tint instead, how can this be achi ...

Warning: Promise rejection was not handled (rejection id: 3)

As a newcomer to the world of await, I'm struggling to handle errors and rejections properly. The unhandled rejections from the shopify-api.js function keep cropping up, and I can't seem to print all the errors that are coming from my middleware ...

Utilizing Node and Express to promptly respond to the user before resuming the program's

I am accustomed to receiving a user's request, handling it, and providing the outcome in response. However, I am faced with an API endpoint that requires about 10 tasks to be completed across various databases, logging, emailing, etc. All of these ta ...

I've been struggling with my Create React app for the past two days, and it just won

When trying to create a React project using the command `npx create-react-app reactproject`, I encountered an error: npm ERR! code ENOENT npm ERR! syscall spawn C:\Users\SUJITKUMAR\Desktop npm ERR! path D:\WebDev\React npm ERR! ...

How can I generate multiple DIV elements within a for loop using JavaScript?

Can a series of unique divs be created using a for loop? for (var i = 0, n = 4; i < n; i++) { var divTag = document.createElement("div"); divTag.id = "div"i; divTag.innerHTML = Date(); document.body.appendChild(divTag); } Is it expected that this scri ...