node.js - Is there a way to isolate native-object extensions in javascript? -
you can extend native objects in javascript. example, sugar.js extends array, string, , function among other things. native-object extensions can useful, inherently break encapsulation - ie if uses same extension name (overwriting extension) things break.
it incredibly nice if extend objects particular scope. e.g. being able in node.js:
// myextension1.js object.prototype.x = 5 exports.speak = function() { var 6 = ({}.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 work right:
// test.js var 1 = require('myextension1') var 2 = require('myextension2') one.speak(); // 6 equals: 6 two.speak(); // 21 equals: 21
of course in reality, print out "6 equals: 21" first one.
is there way, via mechanism, possible? mechanisms i'm interesting in hearing include:
- pure javascript
- node.js
- c++ extensions node.js
unfortunately cannot in node, because node shares same built-in objects across modules.
this bad because brings unexpected side effects, happened in browsers history in past, , that's why yelling "don't extend built-in object".
other commonjs environment following more original commonjs specs, not share built-in object, every module has own. instance in jetpack, mozilla sdk build firefox's add-on, works in way: built-in objects per module , if extend 1 can't clash.
anyway, in general believe extending built-in object nowadays not necessary , should avoided.
Comments
Post a Comment