Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# with
Compile time `with` for strict mode JavaScript
[](http://travis-ci.org/pugjs/with)
[](https://david-dm.org/pugjs/with)
[](https://www.npmjs.com/package/with)
## Installation
$ npm install with
## Usage
```js
var addWith = require('with')
addWith('obj', 'console.log(a)')
// => ';(function (console, a) {
// console.log(a)
// }("console" in obj ? obj.console :
// typeof console!=="undefined" ? console : undefined,
// "a" in obj ? obj.a :
// typeof a !== "undefined" ? a : undefined));'
addWith('obj', 'console.log(a)', ['console'])
// => ';(function (console, a) {
// console.log(a)
// }("a" in obj ? obj.a :
// typeof a !== "undefined" ? a : undefined));'
```
## API
### addWith(obj, src[, exclude])
The idea is that this is roughly equivallent to:
```js
with (obj) {
src
}
```
There are a few differences though. For starters, assignments to variables will always remain contained within the with block.
e.g.
```js
var foo = 'foo'
with ({}) {
foo = 'bar'
}
assert(foo === 'bar')// => This fails for compile time with but passes for native with
var obj = {foo: 'foo'}
with ({}) {
foo = 'bar'
}
assert(obj.foo === 'bar')// => This fails for compile time with but passes for native with
```
It also makes everything be declared, so you can always do:
```js
if (foo === undefined)
```
instead of
```js
if (typeof foo === 'undefined')
```
This is not the case if foo is in `exclude`. If a variable is excluded, we ignore it entirely. This is useful if you know a variable will be global as it can lead to efficiency improvements.
It is also safe to use in strict mode (unlike `with`) and it minifies properly (`with` disables virtually all minification).
## License
MIT