1212function __set__ ( ) {
1313arguments . varName = arguments [ 0 ] ;
1414arguments . varValue = arguments [ 1 ] ;
15+ // Saving references to global objects and functions. Thus a test may even change these variables
16+ // without interfering with rewire().
17+ //@see https://github.com/jhnns/rewire/issues/40
18+ arguments . refs = arguments [ 2 ] || {
19+ isArray :Array . isArray ,
20+ TypeError :TypeError ,
21+ stringify :JSON . stringify
22+ // We can't save eval() because eval() is a *special* global function
23+ // That's why it can't be re-assigned in strict mode
24+ //eval: eval
25+ } ;
1526arguments . src = "" ;
1627arguments . revertArgs = [ ] ;
1728
18- if ( typeof arguments [ 0 ] === "object" && arguments . length === 1 ) {
29+ if ( typeof arguments [ 0 ] === "object" ) {
1930arguments . env = arguments . varName ;
20- if ( ! arguments . env || Array . isArray ( arguments . env ) ) {
21- throw new TypeError ( "__set__ expects an object as env" ) ;
31+ if ( ! arguments . env || arguments . refs . isArray ( arguments . env ) ) {
32+ throw new arguments . refs . TypeError ( "__set__ expects an object as env" ) ;
2233}
2334arguments . revertArgs [ 0 ] = { } ;
2435for ( arguments . varName in arguments . env ) {
2536if ( arguments . env . hasOwnProperty ( arguments . varName ) ) {
2637arguments . varValue = arguments . env [ arguments . varName ] ;
27- arguments . src += arguments . varName + " = arguments.env[" + JSON . stringify ( arguments . varName ) + "]; " ;
38+ arguments . src += arguments . varName + " = arguments.env[" + arguments . refs . stringify ( arguments . varName ) + "]; " ;
2839try {
2940// Allow tests to mock implicit globals
3041//@see https://github.com/jhnns/rewire/issues/35
@@ -34,9 +45,9 @@ function __set__() {
3445}
3546}
3647}
37- } else if ( typeof arguments . varName === "string" && arguments . length === 2 ) {
48+ } else if ( typeof arguments . varName === "string" ) {
3849if ( ! arguments . varName ) {
39- throw new TypeError ( "__set__ expects a non-empty string as a variable name" ) ;
50+ throw new arguments . refs . TypeError ( "__set__ expects a non-empty string as a variable name" ) ;
4051}
4152arguments . src = arguments . varName + " = arguments.varValue;" ;
4253try {
@@ -47,9 +58,12 @@ function __set__() {
4758arguments . revertArgs = [ arguments . varName , undefined ] ;
4859}
4960} else {
50- throw new TypeError ( "__set__ expects an environment object or a non-empty string as a variable name" ) ;
61+ throw new arguments . refs . TypeError ( "__set__ expects an environment object or a non-empty string as a variable name" ) ;
5162}
5263
64+ // Passing our saved references on to the revert function
65+ arguments . revertArgs [ 2 ] = arguments . refs ;
66+
5367eval ( arguments . src ) ;
5468
5569return function ( revertArgs ) {