Error: Unable to execute function abc, it is not defined as a function in this context

Having trouble with a fronted or JavaScript issue where it can't find the defined function in the file. I'm working on integrating Apple Pay and need to call the back-end API based on a specific event. Here is my code.

ACC.payDirect = {
_autoload: ['payDirect'],

session: null,
payDirect: function () {
    let button = $('#mbutton');
    if (button.length === 0) {
        return;
    }

    $('#mbutton').on('click', this.onButtonClicked.bind());

},

onButtonClicked: function () {
    if (!Session) {
        return;
    }

    var request =  getCartPaymentRequest();
    this.requestSession("1234"); //getting error while calling this function
    session.begin();
},


requestSession: function (validationURL) {
    return new Promise(function (resolve, reject) {
        $.ajax({
            type: 'POST',
            url: ACC.config.encodedContextPath + '/checkout/request_session',
            data: JSON.stringify({ validationURL: validationURL }),
            dataType: 'json',
            contentType: 'application/json',
            success: resolve,
            error: reject
        });
    });
},

While trying to call the requestSession function, an error is encountered:

TypeError: this.requestSession is not a function. (In 'this.requestSession("1234")', 'this.abc' is undefined)

I believe there is a basic mistake causing this issue, but I am struggling to pinpoint the exact reason why the second function cannot be found even though the first one works fine.

Answer №1

The issue arises from using the .bind method without passing any parameters.

Consider the sample below:

const obj2 = {
  b: function (callback) {
    callback()
  }
};

const obj = {
  a: function () {
    obj2.b(this.c.bind())
  },
  c: function () {
    console.log(this)
  }
};

obj.a()

In this scenario, the Window object will be displayed in the console.

This is because when JavaScript's bind method runs in a browser, it defaults to the global context, which is the window.

To resolve this, use the .bind method with ACC.payDirect as a parameter to bind it to the object and ensure the correct context. Using this could lead to issues if the method is called with a different context. Alternatively, consider utilizing arrow functions for cleaner code that avoids these complexities.

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

displaying data once "other" is chosen from a dynamic chart

I am having an issue with a dynamic table where I have a dropdown list with the option "other", and I want to display additional input when "other" is selected. Currently, the function I have only hides the input that is always visible and does not show ...

Attempting to incorporate alert feedback into an Angular application

I am having trouble referencing the value entered in a popup input field for quantity. I have searched through the documentation but haven't found a solution yet. Below is the code snippet from my .ts file: async presentAlert() { const alert = awa ...

Unlimited scrolling feature on a pre-filled div container

Looking for a way to implement infinite scroll on a div with a large amount of data but struggling to find the right solution? I've tried various jQuery scripts like JScroll, MetaFizzy Infinite Scroll, and more that I found through Google search. Whi ...

Exploring .ENV Variables using Angular 2 Typescript and NodeJS

After completing the Angular2 Quickstart and tutorials, I'm now venturing into connecting to a live REST Api. I need to include authentication parameters in my Api call, and from what I've gathered, it's best practice to store these paramete ...

Changing the CSS property from "display: none" to "display: block" using JavaScript causes all the div elements to overlap

My issue involves several radio inputs where clicking one should reveal a hidden div containing information. However, when this div appears, it overlaps with the footer instead of staying positioned between the footer and radio input as intended. I am str ...

What is the significance of utilizing app.set() and app.get() in applications?

Is there a way to simplify this code: app.set('port', (process.env.PORT || 3000)); const server = app.listen(app.get('port'), () => { console.log('Server|Port: ', app.get('port')); }); Here is an alternative ...

Supabase's newly uploaded audio blobs are experiencing difficulties when it comes to

I've integrated Supabase storage for storing audio blobs. After retrieving the blob from an API call, it is uploaded successfully to the storage bucket. However, when attempting to play the audio file, nothing happens and the duration shows as 0:00. S ...

What is the process for verifying a particular user in AngularJS?

I'm new to AngularJS and I'm a bit confused about the concepts of GET, PUT requests. I am currently working on an app where I display a list of users on one page, and on another page, I have a form with three buttons. My main focus is on the "Con ...

AngularJS service failing to deliver promised result

I am in the process of retrieving data from my database using AngularJS. I have created a service to fetch the data and a controller to display it. Check out my code snippet: angular.module('myApp') .factory('panelService', [&apos ...

The JQuery app dynamically adds a new input row each time the current input row is filled, repeating this process N

I am looking to dynamically add rows to a table with 3 input fields each. After filling out all the inputs in one row, I want to append a new row with identical input fields. <table> <thead> <tr> <th>H</th> ...

AJAX: Displaying the contents of a folder. Issue with URL resolution

I'm attempting to showcase a collection of images stored in a specific folder within a div. My approach involves utilizing AJAX within a JavaScript file titled edit, which is positioned one directory away from the index route. This implementation is b ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

Instead of leaving an Enum value as undefined, using a NONE value provides a more explicit

I've noticed this pattern in code a few times and it's got me thinking. When you check for undefined in a typescript enum, it can lead to unexpected behavior like the example below. enum DoSomething { VALUE1, VALUE2, VALUE3, } f ...

Exploring Next.js' dynamic routes with an alternative URL approach

Currently in the process of transitioning a React project to Next.js, I've encountered a minor issue with Dynamic Routing that doesn't seem to have any readily available solutions online. I have multiple information pages that utilize the same c ...

How to create a calendar selection input using PHP?

Before I start writing the code myself, I am searching to see if there is already a solution available or if someone has previously outsourced the code. Below is an example of my date selection: I want to create a feature where selecting a month will aut ...

Accessing values from a JSON object in AngularJS without using a loop based on another field

Is there a way to extract the "value" associated with the "name" in JSON using Angular JS without having to iterate through the array? For instance, if I have an array like the one below with name and value fields, how can I retrieve the value "ABC" based ...

Exploring FileReader in conjunction with React and Typescript

I am facing an issue while trying to upload a JSON file using an input element of type file. When I attempt to use the onload method on FileReader in TypeScript, I receive an error message saying "Cannot invoke an object which is possibly 'null'. ...

Encountering a bug in Angular 10 while attempting to assign a value from

I am having trouble updating the role of a user. In my database, I have a user table and a role table with a ManyToMany relation. I can retrieve all the values and even the correct selected value, but I am encountering issues when trying to update it. Her ...

Seeking a light-weight, text-rich editor specifically designed for use on our enterprise website. This editor should be even lighter than TinyMCE

I am in search of a lightweight text editor for an enterprise website, lighter than tinymce with basic buttons for the comment form. It is imperative that the editor also functions properly in IE6. So far, I have tried cleditor 15KB, but it has an issue in ...

Custom properties of an object are being erased when converting to JSON format within the canvas

I am working on a canvas project that involves multiple image objects, each with custom attributes. My goal is to save this canvas as a json object in a database, but the conversion process seems to strip away the custom attributes. Currently, I am using t ...