What is the reason for choosing the term "shadow" over "override" in JavaScript?

Despite my initial assumptions, I found myself unable to discover a definitive answer through numerous Google searches on this topic.

This question pertains to the use of the class pattern in Ecmascript 6 and beyond.

I initially believed that method overriding

in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. Wikipedia

However, I found that Method Shadowing (which goes beyond just block scope 'variable shadowing'- Wikipedia) only seemed to be relevant in a strongly typed language like C#, where an instance of a 'child class' can be set as type 'base class', causing the instance to revert back to the base class methods instead of any 'shadowed' methods.

public abstract class BaseClass
{
    public virtual void shadowedMethod()
    {
        Console.WriteLine("This is the BaseClass version");
    }
}
public class DerivedClass : BaseClass
{
    public new void shadowedMethod()
    {
        Console.WriteLine("This is the Derived child class");
    }
}
public class Program
{
    public static void Main()
    {
        BaseClass instance = new DerivedClass(); // Because BaseClass type is set instead of DerivedClass
        instance.shadowedMethod(); // It prints "This is the BaseClass version"
    }
}

The code was adapted from this article

Therefore, the question arises: why do most JavaScript threads and documentationECMA Standard use override and shadow interchangeably (but tend to favor shadow)? Shouldn't we adopt one term to mitigate confusion? Is there a nuanced difference in JavaScript between overriding and shadowing a method?

Answer №1

After extensive research, I found the definitions related to Javascript to be quite ambiguous. Despite the lack of clarity, I have made an attempt to provide an answer to my own query.

It appears that methods with the same name in the derived class as the base class are referred to as 'shadowed methods'. Additionally, methods that share the same parameters and interface are considered 'overridden' methods, as stated in the article, "Overridden members must accept the same data type and number of arguments" (refer to this article).

A method in a derived class is said to override the parent/base class if it utilizes the same signature (accepting the same parameters):

class BaseClass {
  overriddenMethod(a) {
    return a;
  }
}

class DerivedClass {
  overriddenMethod(a) {
    return 2*a;
  }
}

However, if the method in the derived class accepts different parameters, it is merely 'shadowing' and not overriding:

class BaseClass {
  overriddenMethod(a) {
    return a;
  }
}

class DerivedClass {
  overriddenMethod(a, b) { // This is not overriding because it accepts different parameters.
    return a + b;
  }
}

This concept can be explained further by understanding that in Javascript, being a prototypal language, everything is treated as an object (including Class definitions). As a result, all elements are essentially variables within an object and are subjected to 'variable shadowing' within the prototype chain.

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 is the best way to test a try/catch block within a useEffect hook?

Hey, I'm currently dealing with the following code snippet: useEffect(() => { try { if (prop1 && prop2) { callThisFunction() } else { callThatFunction() } ...

Retrieve the total count of rows present in a specific table

Is there a way to accurately determine the number of rows in a table? I've attempted multiple methods (all unsuccessful) and this is my latest attempt: var _tableOfInterestsCount = wait.Until(x => x.FindElements(By.XPath("//*[@id='gridBody ...

What is the recommended way to include an image in a v-for loop in Vue.js?

I have attempted various online solutions, but I am still unable to display images on the screen. Could it be a simple mistake? The file names and folders are accurate. When providing the path, I aim to retrieve the image associated with the sub-club name ...

It seems like my ajax function is functioning properly, but the data is not getting submitted

Having trouble sending the value of my selector to a PHP file through AJAX. The success function is working, and when I directly visit "your_php_script.php" it functions as expected. However, why is the PHP page not showing up on the page with the AJAX r ...

Using Angular 5 to showcase multiple charts with Chart.js, each chart appearing on its own tab

I have successfully displayed a single chart, but I am facing an issue while trying to display that chart for each tab of a mat-tab-group with different data on each tab. The chart is a part of a larger dashboard consisting of multiple charts, and I have i ...

The THREE.LineSegments - geometry.updateNeeded isn't refreshing

Hello, I'm having trouble updating my THREE.LineSegments using geometry.needsUpdate. In my animation, I am drawing a square side by side in a clockwise motion with each iteration. Even though I can see that the values of the side array are changing co ...

Adjust image source based on media query (CSS or JavaScript)

Is there a way to update the image src based on a media query with a maximum width of 515px? I'm considering using JavaScript, jQuery, or even AngularJS if there is an event equivalent to a CSS media query that can achieve this. I want to have differ ...

What is the best way to pass a JSON object from R to Plumber in a format that JavaScript can interpret as an array instead of

My goal is to receive a JSON raw response from R Plumber and then utilize it in Angular. However, I am encountering an issue where the JavaScript Framework is interpreting it as a string instead of recognizing it as JSON format. "[{\"id&bsol ...

Error: Cannot locate module: Vue not found, incorrect path specified

I am facing an issue with my webpack configuration. I have placed my webpack.config.js and node_modules in a subfolder. When attempting to run the command npm run build, I encounter the following error: ERROR in ../public/Vue/Components/Rating.vue Module n ...

Displaying variables in JavaScript HTML

<script type ="text/javascript"> var current = 0; </script> <h3 style={{marginTop: '10', textAlign: 'center'}}><b>Current Status: <script type="text/javascript">document.write(cur ...

Deletion of component with setTimeout in React Class Component

I have a notification feature that disappears after a certain delay when rendered. The issue arises when attempting to cancel this automatic removal using clearTimeout, as it doesn't seem to work. See below class Notify extends React.Component { ...

Utilize the provided parameter within a JavaScript function

<script type="text/javascript"> function updateTrackName(trackNum) { document.form1.track_(track_number)_name.value=document.form1.track_(track_number)_parent_work.value; } </script> To modify the line inside of the parent_wor ...

Troubleshooting problem with Angular's ng-repeat directive in dealing with varying number of child objects

I am currently dealing with tree-structured data where the parent nodes can have an indefinite number of children, and those children can also have an indefinite number of children, creating a deeply nested structure. While I have successfully formatted th ...

Bidirectional updates in AngularJS with CSS styling

On the backend, certain HTML elements store their position and size persistently and retrieve them when the page loads. These elements can be dragged and resized by users, with any updates needing to be saved on the backend for consistency across sessions. ...

Fade effect not working with Bootstrap Modal

I am encountering an issue with the Twitter Bootstrap modal while trying to display post details on WordPress. The problem is that when the modal opens, the entire screen turns grey and nothing in the modal is clickable. I can only exit this mode by pressi ...

What is the best way to make this relative path function in JavaScript?

My file structure is organized in the following way: multiple folders a subfolder _includes getStatisticsTable.php _templates StatisticsWrapper.html Within StatisticsWrapper.html, I am using jQuery's .get() method to fetch external data which ...

Having difficulty executing the playwright tests

Trying to execute the playwright test from the specified location results in a message prompting to run npm install -D @playwright/test before running the test. Despite having already installed playwright as a dev dependency, the test is still not being ex ...

Utilize Moment to round a date either up or down

I am using Moment to compare two datetime values. Specifically, I am utilizing Moment.isSameOrBefore function. However, my two date values are slightly different due to milliseconds. I want these two values to be considered the same: var date1 = ' ...

The proxy encountered a TypeError when the trap for the property 'set' returned a falsish value

After migrating my code from using es5 class prototype representation to es6 class representation, I encountered an error. This is the comparison of the code before and after migration: ES5 syntax function RoutingScreen (context) { Object.assign(this, ...

Error: The function **now.toUTCString** is not recognized and cannot be executed by HTMLButtonElement

While the JavaScript code runs smoothly without setting a time zone, I encountered an error when trying to display the Barbados time zone. The issue is related to now.toUTCString function throwing the following error message. How can I resolve this? Uncau ...