Reputation: 1925
I am creating a nodejs app, where i have defined classes in separate files. I have written a prototype for Array which i need to be accessed across all the classes how would i implement it, i tried defining the prototype in the main file of the project but i still cant use the prototype in all the classes.
for example
My prototype
Array.prototype.remove = function(e) {
for (var i = 0; i < this.length; i++) {
if (e == this[i]) { return this.splice(i, 1); }
}
};
My project structure
--main.js
--a.js
--b.js
i have my main.js where i require all other js
all the files use the prototype
Upvotes: 2
Views: 1703
Reputation: 2968
If the other files are different modules then, it runs in its own JS context, Best way is to create a module, which will add your example
function to the Array.prototype
then from each module, call this function using require
.
create a module file named extendModule.js and in that add
exports.extendModule = function(constructor) {
constructor.prototype.example = function () {};
}
every other module which needs to extend Array.prototype
require("./extendModule").extendModule(Array)
Upvotes: 4