问题
I'm new to the js world, this is really make me confused, yesterday I was started to cooperate underscore.js in my code, so I start to try it in REPL environment, I choose to use Node console, I came up with var _ = require (./underscore.js)
, then everything works fine.
Today I try to embed it in html by using <script>
tag, it seems I don't need to manually var _ = underscore
, object _
is already there.
someone can explain why, and how to use npm to install underscore globally and require it without specify the file location(like ruby require Module)
回答1:
The main difference is that using a script tag adds all the global bindings of the file's scope to the global scope shared by all the code on the page. When you're writing JavaScript on a website, it's as if all of the different scripts were in one file.
Node's require, on the other hand, much more reasonably does not fill the global scope this way. Instead, it returns an object which contains everything exported by the module; this is basically the module's namespace. This is why you have to do _ = require('./underscore.js')
. This is better because you do not have to worry about different files' global variables conflicting.
来源:https://stackoverflow.com/questions/9132130/whats-the-difference-between-using-require-in-node-console-and-use-script-tag-i