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