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

Using the Jquery UI modal, capturing and passing variables within a form can be achieved without the

Greetings! I am attempting to submit some data using a jQuery modal box in a PHP form. Here is my JavaScript: $( "#dialog-form" ).dialog({ autoOpen: false, height: 500, width: 650, modal: true, buttons: { ...

Show method created by function, substituting the former element on the display

showButtons(1) will show radio buttons for frame number 1, showButtons(400) will display radio buttons for frame number 400. The current code shows all radio buttons for every frame up to 400 HOWEVER, I am aiming for a single set of radio buttons to start ...

What is the best way to utilize the each method within jQuery plugins?

I am relatively new to JavaScript and jQuery plugin development, so please bear with me if this question seems silly. I am struggling with a particular aspect of the following plugin script: (function($){ $.fn.test = function(){ var containe ...

Adding options to a dropdown list dynamically within a ASP.NET Datagrid using Jquery

While the function in my 'aspx' page is functioning properly, I am facing an issue with the 'dropdown' inside the GridControl. It appears to be getting duplicated from the original row and not updating with the values from the appended ...

Can you tell me the significance of the constant variable isType = <T>(type: string) => (obj: unknown): obj is T => toString.call(obj) === `[object ${type}]`?

const isType = <T>(type: string) => (obj: unknown): obj is T => toString.call(obj) === `[object ${type}]` This function is all about determining types, but the arrows used in the syntax are confusing to me. I'm not sure what each arrow s ...

What is the proper way to add a line break within a Custom JSX Tag that is imported from a different class in the code

<Experience startYear={2019} endYear={2019} jobName="First Job" jobDescription="1. Providing API calls support for Headless CMS. 2. Provide escalated ticket/incident management support" ...

When state is updated, the component is re-rendered multiple times

I am working on setting the state in componentDidMount lifecycle method to verify data from local storage. Depending on whether the data exists in local storage, I either redirect the user to the login page or keep them on the dashboard. Is there a way to ...

The CanJS model is unable to retrieve data from a .json file

Implementing MVC using AMD in canjs with requirejs has been my current focus. Here's a look at my domains.json file: [ "1":{"uid": "1","urls": "domain1.abc.com"}, "2":{"uid": "2","urls": "domain2.abc.com"}, "3":{"uid": "3","urls ...

Can you tell me the alternatives for getServerSideProps and getStaticProps in Next.js version 14?

I'm trying to wrap my head around the rendering behavior of SSR/SSG/ISR in Next.js version 14 with the updated app router. Previously, Next.js provided predefined functions like getServerSideProps for server-side fetching and processing (SSR), or getS ...

Incorporate PNG files with pre-defined labels in a React element

In my application, there is a collection of PNG images with filenames consisting of only 2 letters like aa.png, ab.png, ac.png, and so on. Additionally, there is an API endpoint that retrieves an array of objects with a property "name" containing 3 letter ...

Working with double quotes within variable in JavaScript

I am currently working on dynamically creating HTML tags using JavaScript. Please take a look at the code snippet below: function getPhotosSuccess(data) { if (data.d.results.length > 0) { var response = data.d.results; var innerht ...

Neglecting to automatically align text

My goal is to automatically align text based on the language, so that Arabic text starts from the right and English text starts from the left. After some online research, I discovered that I need to use dir="auto" in the tag and text-align: auto; in the CS ...

Is it possible for me to retrieve the error message from my response?

Currently, I am working on displaying backend error messages on the frontend. My approach involves sending a response with an error code and message, then setting a state in my React component to display the error message. While I can successfully display ...

Filtering input that is compatible with Firefox

Attempting to restrict certain special characters (excluding "_" and "-") from being used in a text input field has been a bit of a challenge. I initially tried using regex filtering by pattern, but it didn't work as expected. Then I turned to dynami ...

The Expressjs router prioritizes resolving before retrieving data from Firestore

UPDATE: Upon further investigation, I discovered that by adding "async" to the function signature, the output now displays in the intended order. However, I am still encountering an error regarding setting headers after they have already been sent, even th ...

What is the method for displaying console.log() messages on Heroku?

Lately, I've been making efforts to troubleshoot my app using console.log() within Node.js. Despite adding numerous lines of code for debugging purposes, I have yet to find them in the heroku log no matter how many times I check. $ heroku logs -n 20 ...

Delete the current row in the table before adding a new one with jquery

Having a HTML table and performing updates using Ajax. Everything is functioning properly so far. When clicking on the Edit button, the values are displayed in the textboxes correctly. However, when clicking on the Add button, the table is updated accordin ...

"Enhance your Vue 3 projects with a dynamic library featuring universal components and full

Currently, I am in the process of developing a Vue 3 component library using Vue 3, Vite, and TypeScript. The unique aspect about this library is that it installs as a plugin and registers all components as global entities. Here is an overview of how this ...

Utilizing the content of an HTML element within Ruby embedded code - a comprehensive guide

Below is the code snippet in question: <% @groups.each do |group| %> <tr> <td id="groupid"><%= group.id %></td> <td><a href="#dialog" name="modal"><%= group.title %></a></td> </tr> &l ...

Ways to apply CSS in jQuery using various combinators

I'm facing an issue with changing CSS using jQuery. The specific CSS line I want to modify is: .switch-vertical input ~ input:checked ~ .toggle-outside .toggle-inside { top: 40px; } My attempt at changing it looked like this: $('.switch-vertic ...