javascript challenge with inheritance

I am encountering an issue with two objects where one inherits from the other. The parent object is sending an ajax request to send some contact email.

However, when I use the child object to send the request, all data is empty for some reason. The ajax request is being sent to the correct URL, but the data object is empty.

var contact_A = function(){
    var self = this;
    this.url = '/xxx/xxx/xxx';

    this.constructor = function(){ 

        this.dialog = $('.contact_box');

        this.sender = this.dialog.find('input[name=sender]');
        this.name = this.dialog.find('input[name=name]');
        this.content = this.dialog.find('textarea[name=content]');

        ...
    }

    this.init = function(){
       ...
       this.dialog.find('.button_blue').bind('click', function(){
           var data = self.process_form();
          if(data != false) self.send(data);
        });
        ...
    }

    this.process_form = function(){

        this.validator =  new validator('contact_box', true);
        if(this.validator.validate(true)) {

            var data = {
                sender: this.sender.val(),
                name: this.name.val(),
                content: this.content.val()
            }

            return data;
        } else return false;
    }

    this.send = function(data){

        $.ajax({
            type: "POST",
            url: self.url,
            data: data,
            success: function(msg){
                //if not successful
                self.successful(msg);
            },
            async: true
        });

        this.close();
    }

    ...

    this.constructor();
    this.init();
}

Here is the inheriting object:

var conteact_B = function(){
    var self = this;
    this.constructor();
    this.init();    
}
conteact_B.prototype = new contact_A;
conteact_B.prototype.url = '/yyy/yyy/yyy';

Answer №1

You have blended the prototype object style with the per-instance-members-with-this-closure style of object, which does not function effectively.

The main issue is:

var contact_A = function(){
    var self = this;
    ... perform actions with self ...
};

conteact_B.prototype = new contact_A;

As a result, the value of self will always be the same as what this was during the construction of new contact_A. Essentially, self will consistently refer to the prototype object and not to the specific contact_B instance.

Hence, whenever self is utilized, it will interact with the prototype object rather than the instance; it will not recognize any of the member properties established in the constructor.

To prevent confusion, opt for either prototypes or this-closure objects exclusively. Refer to this discussion for additional insights.

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

Unexpected patterns observed when utilizing parent/child routing files

I am working with a Node/Express backend that is implemented using TypeScript. Whenever I make changes to a file and save it, if I test the root route in Postman localhost:8000/, I receive the expected response. However, when I test localhost:8000/user af ...

Is there a way to insert a value into the input field using JQuery or JavaScript?

After reading my previous post on posting values into an input box, a commenter suggested using JQuery or Javascript. For more code and information, please refer to the link provided above. <label>Date</label>:&nbsp&nbsp <input sty ...

Guide to importing external CSS styles into Angular 2 using the require method

I'm facing an issue with loading an external css file in different environment files. My setup includes two environments: development and production. Loading the css file locally works fine in development mode, but not in production mode. environment ...

obtain the content of a TextField element

In my React component that utilizes MaterialUI, I have created a simple form with a text field and a button: export default function AddToDo() { const classes = useStyles(); return ( <div style={{ display: "flex" }} ...

Utilize the controller data to display information on a day-by-day basis

In my attempt to design a weekly calendar using AngularJS, I am facing challenges when it comes to inserting events into the 7 boxes representing each day of the week on the calendar. The current HTML structure is as follows: <div class="week"> ...

Converting a three.js scene into SVG or alternative vector format for export

Can an SVG- or other vector-formatted image be exported from a scene rendered using three.js's WebGLRenderer? What about from a scene derived from CanvasRenderer? If not, how can one set up SVGRenderer with three.js? Creating a new THREE.SVGRenderer( ...

Alert: VirtualizedList warns of slow updates for a large list despite optimized components

Struggling with avoiding the warning message "VirtualizedList: You have a large list that is slow to update" while utilizing the <FlatList> component in React-Native. Despite thorough research and attempts at finding a solution, including referencin ...

The expo-location feature is failing to accurately record and store all of the positions within the array

Incorporating expo-location in my react-native app, I utilize it to track the user's positions and store them in a redux object. While debugging the object reveals that all positions have been successfully inserted, upon retrieving this array, it turn ...

When using <body onload=foo()>, the function foo will not be executed

Having trouble with this code - it seems like initialize() is not being called. Check out the code here Any insight into why this might be happening? ...

Javascript code not running as expected

Check out this code snippet: function generateRandomTeams() { const prom = new Promise(() => { // ... console.log('teams', props.state.teams) // logs }) .then(() => { console.log('here') // doesn't log }) ...

Converting CSV to JSON in Node.js with dual values for one column in a row

Having a csv file where some rows contain two values for a column, I am currently attempting to split using ,, but the results are not as expected. Can anyone provide insight on how to achieve the desired output without utilizing any npm libraries? //us ...

Saving Data in an Angular Material Table: A How-to Guide

I have a basic angular material table and I am looking for a way to save the data displayed in each row when a button is clicked. Is it possible to save each row of data as an object and push it to an array? If so, how can I achieve this? <div class=& ...

Showing Data from JSON on an HTML Page

My project in play framework requires displaying Strings from a Json (containing a list of Strings) in a table on an html page. I attempted to use ajax and jquery for this purpose, but the implementation is not functioning correctly. Here is my javascript ...

Evaluate JavaScript code on the client side that modifies the DOM without using a browser through programming

Is it feasible to achieve something similar to this scenario: Send a request to the website I am trying to scrape. The website utilizes client-side and potentially server-side JavaScript to make requests and modify the Document Object Model (DOM). For e ...

Trouble displaying custom markers in VueJS using Google Maps API

I have integrated vue2-google-maps to display a map and add markers on specific locations. Here is the code snippet showing the map components along with the props passed to it. <gmap-map id="map" :center="center" :zoom="5" ...

Explore the search bar with functional filtering for JSON items

I'm currently working on creating a dynamic filter bar integrated with a search functionality. My data is stored in JSON format, including details such as artist name, title, source, and more. Despite successfully retrieving results through console.lo ...

Function call does not match any existing functions

Recently, I have started learning about Inheritance... #include<iostream> using namespace std; class base { public: void show() { //implementation goes here } }; class derive : public base { public: ...

Creating a Runescape Tracker: What essentials should I include?

Hello everyone, I am a beginner in the world of programming and I am excited to learn. I have heard that the best way to learn is by working on a project. I have always been interested in creating a Skill Tracker for my clan. Can you offer any advice on wh ...

Attempting to retrieve exclusively the checked records in Vue.js

Currently, I am referring to this library for checkboxes. As I delve into the code, I notice how it is declared and utilized. Initially within the el-table, we have @selection-change="handleSelectionChange". They have initialized an empty array ...

Ensure that the sidebar automatically scrolls to the bottom once the main content has reached the bottom

I am facing an issue with a sticky sidebar that has a fixed height of calc(100vh-90px) and the main content. The sidebar contains dynamic content, which may exceed its defined height, resulting in a scrollbar. On the other hand, the main content is lengthy ...