(#88) - Fix nodejs check #89

Merged
merged 1 commit into from Mar 10, 2014

2 participants

@benrudolph

No description provided.

@benrudolph

Ok here goes my best attempt at reasoning about why this check will work:

Proposed solution for checking whether library belongs is being loaded in node.js or the browser.

Current check:

typeof module != 'undefined' && module.exports

Proposed check:

typeof module != 'undefined' && module.exports && this.module !== module

Problem:

When the browser has other libraries loaded that define module and have a module.exports property, store.js believes incorrectly that it is in node.js.

Browser:

The check this.module !== module will always return false when in the browser if module is defined. The this context of a script being loaded is defaulted to window. Thus when we call this.module we are essentially calling window.module. When we leave off the this, a reference to module will cause the browser to check for a definition of it in the global namespace. If the global namespace has been polluted with a variable called module, then that is equivalent to calling window.module, which is equivalent to calling this.module and therefore showing that this.module === module in the context of a browser. By contradiction, this.module !== module will always be false when loading in a browser.

Node.js:

When nodejs loads a module using the require function which is how you would use storejs in node, it resets the this object to an empty object. Since you know the this object has been reset to an empty object, one can be certain that this.module !== module will always return to true.

The reseting of the this object can easily be tested by doing:

global.localStorage = require('localStorage');
this.alphabet = 'abc'
var store = require('./store');

And then adding a line in store.js that logs this.alphabet. It will be undefined (and so will this.module).

@marcuswestin
@benrudolph

Thanks for taking a look. great lib

@marcuswestin marcuswestin merged commit 6ce6e64 into marcuswestin:master Mar 10, 2014
@marcuswestin

Merci!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment