Skip to content
Advertisement

Add or override properties of already defined function JavaScript

I have a JavaScript function with the following structure:

function someFunctions() {
  this.DOSOMETHING = function(parameters){
    //some logic
  }
}

This is loaded in another file and instantiated as an object that is then being used:

load('file_containing_someFunctions.js')
var someFunctions = new someFunctions();

function doTheThing(parameters) { 
  //some logic
  someFunctions.DOSOMETHING(parameters)
}

I would like to load another file after the first one which overrides or adds properties to someFunctions() before the object is instantiated.

load('file_containing_someFunctions.js')
load('file_containing_extended_functions.js')
var someFunctions = new someFunctions();

function doTheThing(parameters) { 
  //some logic
  someFunctions.DOSOMETHINGELSE(parameters)
}

How should I define DOSOMETHINGELSE in file_containing_extended_functions.js? Is it possible? It’s worth noting that the code is rather old and used in old browsers.

Advertisement

Answer

By using the new keyword, you are instantiating a new object whose constructor function is someFunctions. The constructor creates a function called DOSOMETHING and assigns it as a property of the newly created object. This goes against the OOP paradigm in JavaScript where object methods should be members of the object’s prototype, not the object itself.

You may transform the constructor code as follows:

function someFunctions() { }
someFunctions.prototype.DOSOMETHING = function(parameters) {}

In your extension script you may then add and override methods by modifying the someFunctions.prototype object.

If you insist on keeping the current implementation of someFunctions, you may create a new function with the same name, internally calling the old someFunctions constructor and modifying the returned object:

const oldSomeFunctions = someFunctions;

var someFunctions = function() {
    const base = new oldSomeFunctions();
    base.DOSOMETHING = console.log;
    base.DOSOMETHINGELSE = console.info;
    
    return base;
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement