Skip to content
Advertisement

Add or override properties of already defined function JavaScript

I have a JavaScript function with the following structure:

JavaScript

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

JavaScript

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

JavaScript

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:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement