04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4: Variables, Scope, and Memory<br />

Determining Type<br />

The typeof operator, introduced in the previous chapter, is the best way to determine if a variable is a<br />

primitive type. More specifically, it ’ s the best way to determine if a variable is a string, number, Boolean,<br />

or undefined . If the value is an object or null , then typeof returns ” object ” as in this example:<br />

var s = “Nicholas”;<br />

var b = true;<br />

var i = 22;<br />

var u;<br />

var n = null;<br />

var o = new Object();<br />

alert(typeof s);<br />

alert(typeof i);<br />

alert(typeof b);<br />

alert(typeof u);<br />

alert(typeof n);<br />

alert(typeof o);<br />

//string<br />

//number<br />

//boolean<br />

//undefined<br />

//object<br />

//object<br />

Although typeof works well for primitive values, it ’ s of little use for reference values. Typically, you<br />

don ’ t care that a value is an object — what you really want to know is what type of object it is. To aid in<br />

this identification, ECMAScript provides the instanceof operator, which is used with the following<br />

syntax:<br />

result = variable instanceof constructor<br />

The instanceof operator returns true if the variable is an instance of the given reference type<br />

(identified by its constructor function). Consider this example:<br />

alert(person instanceof Object); //is the variable person an Object?<br />

alert(colors instanceof Array); //is the variable colors an Array?<br />

alert(pattern instanceof RegExp); //is the variable pattern a RegExp?<br />

All reference values, by definition, are instances of Object , so the instanceof operator always returns<br />

true when used with a reference value and the Object constructor. Similarly, if instanceof is used<br />

with a primitive value, it will always return false because primitives aren ’ t objects.<br />

The typeof operator also returns “ function ” when used on a function. When used<br />

on a regular expression, typeof incorrectly returns “ function ” as well.<br />

Execution Context and Scope<br />

The concept of execution context, referred to as context for simplicity, is of the utmost importance in<br />

JavaScript. The execution context of a variable or function defines what other data it has access to, as<br />

well as how it should behave. Each execution context has an associated variable object upon which all of<br />

84

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!