JavaScript Redefining Functions

Functions have the ability to override behavior. Overriding occurs by assigning an anonymous function to a variable that has the same name as the overridden function:

  
display(){
    console.log("Good morning");
    display = function(){
        console.log("Good afternoon");
    }
}

display(); // Good morning
display(); // Good afternoon

When the function is triggered for the first time, the main block of function operators is active, in particular, in this case, the message “Good morning” is displayed. And when the display function is fired for the first time, it is also redefined. Therefore, on all subsequent calls to the function, its redefined version is triggered, and the message “Good afternoon” will be displayed on the console.

But when redefining a function, some nuances must be taken into account. In particular, let’s try to assign a function reference to a variable and call the function through this variable:

  
display(){
    console.log("Good morning");
    display = function(){
        console.log("Good afternoon");
    }
}

// assigning a function reference before redefining
var displayMessage = display;
display(); // Good morning
display(); // Good afternoon
displayMessage(); // Good morning
displayMessage(); // Good morning

Here, the displayMessage variable gets a reference to the display function before it is redefined. Therefore, when displayMessage() is called, the unoverridden version of the display function will be called.

But let’s say we defined the displayMessage variable after calling the display function:

 
display(); // Good morning
display(); // Good afternoon
var displayMessage = display;
displayMessage(); // Good afternoon
displayMessage(); // Good afternoon

In this case, the displayMessage variable will point to the overridden version of the display function.