Ray
Ray

Reputation: 370

Extending native JS objects in Node.js?

Is there a node.js way to extend native JS objects, similar to clientside:

Date.prototype.tomorrow = function(){
  return this.getTime()+86400000;
}

such that

var dt = new Date();
dt.tomorrow();

works as expected.

Upvotes: 0

Views: 1324

Answers (2)

alessioalex
alessioalex

Reputation: 63673

This works exactly like in the browser, since Node is built on top of V8 (Google Chrome's engine). Save the following code and run it with Node:

Date.prototype.tomorrow = function(){
  return this.getTime()+86400000;
}
var dt = new Date();
console.log(dt.tomorrow());

Upvotes: 3

sczizzo
sczizzo

Reputation: 3206

That ought to work. Prototypes are a plain old JavaScript feature, not Node-specific. In fact, this is what the Sugar library does, but you should read their notes on this.

Upvotes: 1

Related Questions