5
5
* All variables within this function are namespaced in the arguments array because every
6
6
* var declaration could possibly clash with a variable in the module scope.
7
7
*
8
- *@param {! String|! Object } varName name of the variable to set
8
+ *@param {String|Object } varName name of the variable to set
9
9
*@param {String } varValue new value
10
10
*@throws {TypeError }
11
11
*@throws {ReferenceError } When the variable is unknown
12
12
*@return {* }
13
13
*/
14
-
15
14
function __set__ ( ) {
16
15
arguments . varName = arguments [ 0 ] ;
17
16
arguments . varValue = arguments [ 1 ] ;
18
17
arguments . src = "" ;
19
- var snapshot = { } ;
18
+ arguments . snapshot = { } ;
20
19
21
20
if ( typeof arguments [ 0 ] === "object" && arguments . length === 1 ) {
22
21
arguments . env = arguments . varName ;
@@ -27,40 +26,44 @@ function __set__() {
27
26
if ( arguments . env . hasOwnProperty ( arguments . varName ) ) {
28
27
arguments . varValue = arguments . env [ arguments . varName ] ;
29
28
arguments . src += arguments . varName + " = arguments.env." + arguments . varName + "; " ;
30
- snapshot [ arguments . varName ] = eval ( arguments . varName ) ;
29
+ arguments . snapshot [ arguments . varName ] = eval ( arguments . varName ) ;
31
30
}
32
31
}
33
32
} else if ( typeof arguments . varName === "string" && arguments . length === 2 ) {
34
33
if ( ! arguments . varName ) {
35
34
throw new TypeError ( "__set__ expects a non-empty string as a variable name" ) ;
36
35
}
37
36
arguments . src = arguments . varName + " = arguments.varValue;" ;
38
- snapshot [ arguments . varName ] = eval ( arguments . varName ) ;
37
+ arguments . snapshot [ arguments . varName ] = eval ( arguments . varName ) ;
39
38
} else {
40
39
throw new TypeError ( "__set__ expects an environment object or a non-empty string as a variable name" ) ;
41
40
}
42
41
43
42
eval ( arguments . src ) ;
44
- return function ( ) {
45
- __set__ ( snapshot ) ;
46
- } ;
43
+
44
+ return function ( snapshot ) {
45
+ __set__ ( snapshot ) ;
46
+ } . bind ( null , arguments . snapshot ) ;
47
47
}
48
48
49
49
function __with__ ( ) {
50
- var args = arguments ;
51
- return function ( callback ) {
52
- if ( typeof callback !== "function" ) {
53
- throw new TypeError ( "__with__ expects a callback function" )
54
- }
50
+ var args = arguments ;
55
51
56
- var undo = __set__ . apply ( null , args )
57
- try {
58
- callback ( ) ;
59
- }
60
- finally {
61
- undo ( ) ;
52
+ return function ( callback ) {
53
+ var undo ;
54
+
55
+ if ( typeof callback !== "function" ) {
56
+ throw new TypeError ( "__with__ expects a callback function" )
57
+ }
58
+
59
+ undo = __set__ . apply ( null , args ) ;
60
+
61
+ try {
62
+ callback ( ) ;
63
+ } finally {
64
+ undo ( ) ;
65
+ }
62
66
}
63
- }
64
67
}
65
68
66
- module . exports = { "__set__" :__set__ , "__with__" :__with__ }
69
+ module . exports = { "__set__" :__set__ , "__with__" :__with__ } ;