Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to change objects prototypes in node.js?

I want to add or override some standard methods of Object, Function and Array (e.g., like suggested in this answer) in node.js application. How should I do all the "patches" in just one module so that it affects all my other modules?

Will it be enough if I do it in a module that is just require'd or it won't work because the two modules have different global namespaces so they have different Object?... Or should I run some initialisation function after require that makes all these "patches" working in this module too?

like image 537
esp Avatar asked Jan 15 '13 00:01

esp


People also ask

How do you set the prototype of one object to another?

The Object. setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null. All JavaScript objects inherit properties and methods from a prototype. It is generally considered the proper way to set the prototype of an object.

How do I access prototype objects?

We can access the function's prototype property using functionName. prototype . As seen from the above image prototype property of the function is an object (prototype object) with two properties: constructor property which points to Human function itself.

Can we change prototype?

Changing Prototype As mentioned above, each object's prototype is linked to function's prototype object. If you change function's prototype then only new objects will be linked to changed prototype. All other existing objects will still link to old prototype of function.

What are object prototypes in JS?

Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.


2 Answers

//require the util.js file 
require('./util.js');

var a = [];
a.doSomething();

in your "util.js" file:

//in your util.js file you don't have to write a module, just write your code...
Array.prototype.doSomething = function(){console.log("doSomething")};
like image 177
user934801 Avatar answered Sep 19 '22 10:09

user934801


Each file loaded shares the same primordial objects like Object, Array, etc, unless run in a different vm Context, so requiring the file once in your initialization will make the changes everywhere.

like image 22
ckknight Avatar answered Sep 19 '22 10:09

ckknight