1

習慣なのかもしれませんし、一貫性のためかもしれませんがvar、モジュールのルート スコープで がそれほど多く使用されているのはなぜでしょうか (多くのコード例がそれを示しています)。本当に必要ですか?つまり、モジュールはルート スコープなので、変数を宣言したかどうかに関係なくvar、両方の状況で同じオブジェクトにアタッチしますよね? 名前空間がごちゃごちゃしていませんか?

qs = require('querystring'); // looks better than

var qs = require('querystring'); // right?
4

1 に答える 1

4

The reason is that Common JS modules are not only used in node.js but also in a variety of other environments.

Many Common JS modules can be used in browsers as well. Each module gets its own function wrapper to isolate it from other modules. In that case it's necessary to use var so that you don't accidentally leak into the global scope.

That being said most developers prefer to use var explicitly in their code for the following reasons:

  1. It's a good programming practice. Seriously, programming is all about practice. I'm so used to declaring variables using var that I often find myself using var declarations in C/C++ and then have the compiler cry at me.
  2. Variables declared using var cannot be deleted using the delete operator. Sometimes I purposely omit var in global variables so that I can delete them later and operate in "ninja mode".
于 2013-03-16T06:12:20.733 に答える