What happens to the parent scope in Javascript when declaring a subclass and why does it get overridden?

I have two classes in JavaScript, with one inheriting from the other. The structure is as follows:

var Parent = (function(){
    var self;

    var parent = function(){
        self = this;
        self.type = 'Parent';
    };

    parent.prototype.getType = function(){
        return self.type;
    };

    return parent;
})();

var Child = (function(){
    var self;

    var child = function(){
        self = this;
        Parent.call(self);
        self.type = 'Child';
    };

    child.prototype = Object.create(Parent.prototype);
    child.prototype.constructor = child;

    return child;
})();

However, when I create an instance of Child, it changes the value of self in the Parent class:

var parentInstance = new Parent();
var childInstance = new Child();
console.log(parentInstance.getType());
console.log(childInstance.getType());

The output is:

Child // I expected Parent
Child

I have a couple of questions:

  • Why does this happen? I assumed that self, defined in the Parent class, would be a private variable unique to each Parent instance.
  • I prefer wrapping my class definitions in a closure for organization, but I encounter issues like needing the self variable to access class scope for private methods.

    For example:

    var Parent = (function(){
        //...
        function _getType(){
            return self.type; // 'this.type' is undefined here
        }
    })();
    

    Is there a way to address this problem while still using the closure structure?


EDIT: solution for calling "private" methods

In _getType, using this would reference the Parent class instead of the object being created (e.g.,

parentInstance</code), so the issue can be resolved like this:</p>

<pre><code>var Parent = (function(){
    var parent = function(){
        this.type = 'Parent';
    };

    parent.prototype.callPrivateGetType = function(){
        return _getType(this);
    };

    function _getType(that){
        return that.type;
    }
}

Now, running

var parentInstance = new Parent();
var childInstance = new Child();
console.log(parentInstance.callPrivateGetType());
console.log(childInstance.callPrivateGetType());

Will produce:

Parent
Child

Answer №1

self is not considered a "private variable" in JavaScript, as the language does not have private variables or classes. While you can colloquially refer to them as such, it's important to remember that these concepts do not directly translate from other programming languages.

In this specific scenario:

  • The self variable is locally defined within the getType method.
  • During evaluation:
    • The IIFE on the right side of the Sup assignment is evaluated.
    • self becomes a local variable known as SupSelf
    • The sup constructor is defined.
    • The getType method is attached to it, forming a closure over SupSelf.
    • The prototype of sup is returned from the IFFE and assigned to Sup.
  • When sub.getType() is called:
    • this refers to sub, and Sup.prototype.getType is evaluated.
    • Within getType, self represents the closed-over SupSelf, which retains the value of Sup assigned by new Sup(). It cannot access the self value inside Sub since it is not local to it.

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

What could be the reason for jQuery not functioning properly as needed?

function toggleDisplayingRooms(nameSelect){ if(nameSelect){ firstroom = document.getElementById("firstroom").value; secondroom = document.getElementById("secondroom").value; thirdroom = ...

Redux - The same reducers, containers, and components are yielding varying outcomes

update: Issue resolved by connecting a different variable to the mapStateToProps. I'm encountering some challenges with my react-redux application and I'm struggling to pinpoint the error in my setup. You can access the source code here. The f ...

What is the best way to transfer information between different pages in an HTML document?

I am facing a specific requirement where I must transfer form data from one HTML page to another HTML page. The process involves a total of 5 pages, with the user entering data in the following order: 1st page: Name 2nd page: Weight 3rd page: Height 4t ...

Tips on automating the process of moving overflowing elements into a dropdown menu

Challenge Description In need of a dynamic navigation bar, I faced the problem of displaying only the first X items on one line and have the remaining items hidden in a "Show more" dropdown. The challenge was to calculate the width of each item accurately ...

"Pairing Angular's loader with RxJS combineLatest for seamless data

Hey there! Currently, I'm working on enhancing my Angular application by implementing a global loader feature. This loader should be displayed whenever data is being fetched from my API. To achieve this, I am utilizing ngrx actions such as fetchDataAc ...

Update a specific line in a file with node.js

What is the most efficient way to replace a line in a large (2MB+) text file using node.js? Currently, I am accomplishing this by Reading the entire file into a buffer. Splitting the buffer into an array by the new line character (\n). Replacing th ...

Angular variable resets to initial value after modification

Currently, I am utilizing ui-router to handle the state management for the admin segment of a project. The admin area includes the ability to browse through various categories. In this category management module, I am working on implementing a breadcrumb l ...

Troubleshooting: Else block not functioning as expected within a React JS map function

I have a notification feature that makes an API call every 10 seconds to display an alert based on the response. However, I'm encountering an issue where the div is not being rendered properly. The div should be displayed based on certain conditions w ...

By checking the active box and completing the fields, the button will be activated

I'm currently working on a form that requires all fields to be filled out and the acceptance checkbox to be checked before the Submit button becomes active. If any entry or the checkbox is subsequently removed, the button should become inactive again. ...

The module 'iap_verifier' could not be located

Setting up a new server using the following repository - https://github.com/surespot/web-server. I have successfully installed node.js, npm, CoffeScript, and all required dependencies. apt-get install nodejs npm npm install -g <a href="/cdn-cgi/l/email ...

Swap out the content in a text input box with the text chosen from a suggested autocomplete option

I am working on a text input box with auto-complete options displayed below it. I want to enable users to navigate through the options using keyboard arrows and "select" one, causing it to change color. How can I update the text in the input box with the s ...

Develop a plugin architecture using JavaScript and Node.js

Here is a basic implementation using node.js with express: var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('Hello World'); }); app.listen(3000); I am interested in creatin ...

Having numerous calls to isNaN within a JavaScript if-else statement

I've created a JavaScript function that generates div elements and styles them based on user input values. However, I'm facing an issue when trying to display a warning message if the input is not a number. Currently, I'm unable to create th ...

Is it possible to extract an attribute value from a parent element using ReactJS?

https://i.stack.imgur.com/OXBB7.png Whenever I select a particular button, my goal is to capture the {country} prop that is linked to it. I attempted the following approach import React, { useState, useEffect } from 'react' import axios from &ap ...

Instead of uploading multiple files at once, allow users to upload individual files by clicking on the table row

In my dynamic table, there are 4 columns. The first 3 columns in each row have an input type='file' where users can choose a file to upload, and the 4th column has a submit button aligned with the rows. While submitting files in the first row wor ...

Tips on altering the color of a circle's radius within Google Maps

I'm trying to add a circular radius on a Google Map. Even after reviewing the Google Maps API documentation, I'm still unsure of how to accomplish this task. Below is the code snippet I have been working with: const MyMapComponent = compose( ...

Transforming a detailed JSON structure into a more simplified format with Angular 2

As a newcomer to Angular 2, I find myself encountering a hurdle in filtering unnecessary data from a JSON object that is retrieved from a REST API. Below is an example of the JSON data I am working with: { "refDataId":{ "rdk":1, "refDataTy ...

Automatically Refresh a Div Element Every 5 Seconds Using jQuery's setInterval() Function

My goal is to refresh the left div every 5 seconds using $.ajax to get JSON data and display 4 random elements in that div. However, even though the left div block refreshes, the content remains the same with the same images always showing. view image desc ...

Avoid having the toast notification display multiple times

I've been working on implementing a toast notification for service worker updates in my project. However, I'm facing an issue where the toast notification pops up twice. It seems to be related to the useEffect hook, but I'm struggling to fig ...

how to display ajax response in webpage using jQuery

I need to perform multiple ajax calls in a for loop, with each call returning a text/html response that needs to be printed. Here is the code I have implemented: function printBill(printBills, lastBillNo, type,taxType,outletId,date){ var printableObjects ...