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

Activate the jQuery click event by specifying the URL

On my webpage, I have a jQuery click function that loads multiple HTML pages into a specified div. I am looking to set specific URLs that will trigger this event, like test.com#about <script type="text/javascript"> $(document). ...

Combining a JavaScript NPM project with Spring Boot Integration

Recently, I built a frontend application in React.js using NPM and utilized IntelliJ IDEA as my IDE for development. Additionally, I have set up a backend system using Spring Boot, which was also developed in IntelliJ IDEA separately. My current goal is t ...

Incorporating multiple web services into a React JS project to populate a Material UI dropdown efficiently

I have some code that is calling a web service and I have a few questions. Firstly, what is the best way to call a second web service? Currently, I am calling one and displaying the data in a list. But if I need to call a second web service, should I also ...

Customize node.js response by overriding or adding another return statement

I have two variables, FirstName and LastName, that I need to include in the response data. It is important to note that the FirstName and LastName are not stored in the Student table. let result = await Student.get(id) let FirstName = "Paul" let LastName ...

What are some ways to enhance Redux's performance when handling rapid updates in the user interface?

I have been facing a challenge with integrating a D3 force graph with my redux state. During each 'tick' update, an action is dispatched to update a collection of positions in the redux state. These positions are then combined with node data to u ...

Create a new build for testing and debugging using create-react-app

Currently, I am in the process of developing a web application that utilizes a React frontend and is powered by a golang api layer. Although I do not have extensive experience with Javascript, I find myself struggling with the Node build system. I am loo ...

Swapping out a sequence of characters in a web address with a different set

Swapping out imgur for filmot, Enter URL - https://i.stack.imgur.com/Uguvn.jpg Click the submit button After clicking submit, a new tab should open with the link .filmot.com/abcde.jpg. <html> <head> <title>input</title> <sc ...

Can the `XMLHttpRequest` object stay active when the user switches to a different page?

I am currently facing an issue on my website where users can submit a form using AJAX. The response is displayed in an alert indicating whether the submission was successful or if there were any issues. However, due to the asynchronous nature of this proce ...

React Intersection Observer Triggering Memory Leaks

Issue Description: I encountered a problem with my React app crashing on mobile. The Chrome dev tools revealed that garbage collection wasn't triggering, and upon inspecting the heap, I found that the top constructors by retained size were all linked ...

How should I proceed if a TypeScript definition file that I am relying on is lacking a specific definition?

I have encountered an issue while using the React type definitions for my project. The focus method is missing on elements in the array returned by the refs property, which prevents me from getting a specific example to work. The compiler error states: pro ...

Execute the knockout function using jQuery

There's a scenario where I am trying to trigger a knockout method using jQuery. The Knockout viewModel has already been bound, but I'm unsure of how to call it using jQuery. Below is the snippet of my code: $(document).ready() { form_submit( ...

I'm encountering an issue with my array in JavaScript while using // @ts-check in VS Code. Why am I receiving an error stating that property 'find' does not exist on my array? (typescript 2.7

** update console.log(Array.isArray(primaryNumberFemales)); // true and I export it with: export { primaryNumberFemales, }; ** end update I possess an array (which is indeed a type of object) that is structured in the following manner: const primar ...

When the 'keyup' event is detected, trigger the function only on keyup

Looking for assistance in setting this to only trigger on keyup events. Can anyone provide guidance? $(function() { $('#acf-field_5a32085c7df98-field_5a3208f87df99').on('keyup', function() { $('#link-headline-fb').text($( ...

Trigger Javascript on 'Nearby' input from Html form

I have a JavaScript code that retrieves the latitude and longitude of users from their device for a local search. Although everything works correctly, I want to make sure the script is only executed if the user specifically selects "nearby" as the locatio ...

Is there a way to consistently apply default props to a styled component?

Currently, I am working with React, Material UI, and Styled Components. My goal is to create a personalized Input field where the size='small' is always passed as a prop to my component. To clarify, if the user neglects to include the size attri ...

When I try to run Parcel, my ReactJS website just won't deploy in a serverless environment

For a while now, I've been working on a website using serverless. Everything was going smoothly until this morning when I encountered an issue with pushing updates from my site to the serverless platform. When trying to push, I received the following ...

Adjust the font size based on the dimensions of the container

I'm currently working on a script that dynamically sets the font-size based on the container's dimensions and the length of the text. This is what I have implemented so far. window.onload = function () { var defaultDimensions = 300; ...

Enable automatic scrolling when a button on the previous page has been clicked

Imagine there are two buttons (Button 1 and Button 2) on a webpage (Page A). Clicking on either button will take you to the same external page (Page B). How can we ensure that Button 1 takes you to the top of Page B, while Button 2 automatically scrolls do ...

Tips for creating a reusable function in React.js?

I have a script that executes on input focus and passes certain values based on a specific logic. I would like to reuse this script for multiple input fields that trigger the focus event. How can I accomplish this? This is my current script: <input ...

Working with npm objects across multiple files

My goal is to integrate the npm package for parallax (lax.js) into my project. The documentation states that in order to initialize it, the following code snippet should be included: window.onload = function () { lax.init() // Add a driver that we use ...