B T
B T

Reputation: 60875

Is there a way to isolate native-object extensions in javascript?

You can extend native objects in javascript. For example, sugar.js extends Array, String, and Function among other things. Native-object extensions can be very useful, but inherently break encapsulation - ie if someone uses the same extension name (overwriting another extension) things will break.

It would be incredibly nice if you could extend objects for a particular scope. E.g. being able to do something like this in node.js:

// myExtension1.js
Object.prototype.x = 5

exports.speak = function() {
  var six = ({}.x+1)
  console.log("6 equals: "+six)
}

// myExtension2.js
Object.prototype.x = 20

exports.speak = function() {
  var twenty1 = ({}.x+1)
  console.log("21 equals: "+twenty1)
}

and have this work right:

// test.js

var one = require('myExtension1')
var two = require('myExtension2')

one.speak(); // 6 equals: 6
two.speak(); // 21 equals: 21

Of course in reality, this will print out "6 equals: 21" for the first one.

Is there any way, via any mechanism, to do something where this is possible? The mechanisms I'm interesting in hearing about include:

Upvotes: 3

Views: 200

Answers (2)

ZER0
ZER0

Reputation: 25322

Unfortunately you cannot do that currently in node, because node shares the same built-in objects across modules.

This is bad because it could brings to unexpected side effects, like it happened in the browsers history in the past, and that's why now everyone is yelling "don't extend built-in object".

Other commonJS environment are following more the original commonJS specs, so that you do not share built-in object, but every module has its own. For instance in jetpack, the Mozilla SDK to build Firefox's add-on, it works in this way: so you the built-in objects are per module and if you extend one you can't clash.

Anyway, in general I believe that extending built-in object nowadays is not really necessary and should be avoided.

Upvotes: 2

Evan Borden
Evan Borden

Reputation: 301

This is not possible since a native type only has a single source for its prototype. In general I would discourage mucking with the prototype of native types. Not only are you limiting your portability (as you pointed out), but you may also be unknowingly overwriting existing properties or future properties. This also creates a lot of "magic" in your code that a future maintainer will have a hard time tracking down. The only real exception to this rule is polyfils. If your environment has not implemented a new feature yet then a polyfil can provide you this.

Upvotes: 0

Related Questions