HTML and CSS Reference
In-Depth Information
Variables and hoisting
Hoisting is a JavaScript feature that allows developers to declare variables everywhere in the scope
and then use them everywhere. In JavaScript, you are allowed to first use the variable and then
declare it (such as, var ) later. The overall behavior is just as if the var statement were placed at the top.
Here's an example:
function() {
mode = 1;
...
var mode;
}
Historically, this feature was introduced to keep the entry barrier to JavaScript for non-expert
developers as low as possible. When you use JavaScript to write significant portions of code, however,
hoisting is a clear source of confusion and becomes error prone. It's a good habit to place all your
variables at the top of each function, even better if you place them in a single var statement as shown
below:
function() {
var start = 0,
total = 10,
index;
...
}
Note that having multiple var statements, instead, is neither bad nor wrong. However, sticking to
the single var approach helps force you to always define a variable before you use it.
Dealing with objects
JavaScript is not usually catalogued as an object-oriented language, at least not at the same level as
Java and C#. The primary reason for this is the definition of an object that you get from JavaScript is
different from the commonly accepted idea of an object that you get from classic object-oriented
languages.
Structure of JavaScript objects
In JavaScript, an object is a dictionary of name/value pairs. The blueprint of the object is implicit and
you have no way to access it. A JavaScript object usually only has data, but you can add behavior. The
(explicit) structure of an object may change at any timeā€”for example, you can add new methods and
properties at run time. The implicit structure never changes. Here's how you can add a new property
to an existing object:
var theNumber = new Number();
theNumber.type = "Number";
Search WWH ::




Custom Search