06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 1<br />

The instanceof operator<br />

One of the problems with using reference types to store values has been the use of<br />

the typeof operator, which returns object no matter what type of object is being<br />

referenced. To provide a solution, you can use the instanceof operator. Let's see<br />

some examples:<br />

var aStringObject = new String("string");<br />

console.log(typeof aStringObject); //"object"<br />

console.log(aStringObject instanceof String); //true<br />

var aString = "This is a string";<br />

console.log(aString instanceof String); //false<br />

The third line returns false. We will discuss why this is the case when we discuss<br />

prototype chains.<br />

Date objects<br />

<strong>JavaScript</strong> does not have a date data type. Instead, you can use the Date object<br />

and its methods to work with dates and times in your applications. A Date object<br />

is pretty exhaustive and contains several methods to handle most date- and timerelated<br />

use cases.<br />

<strong>JavaScript</strong> treats dates similarly to Java. <strong>JavaScript</strong> store dates as the number of<br />

milliseconds since January 1, 1970, 00:00:00.<br />

You can create a Date object using the following declaration:<br />

var dataObject = new Date([parameters]);<br />

The parameters for the Date object constructors can be as follows:<br />

• No parameters creates today's date and time. For example, var today = new<br />

Date();.<br />

• A String representing a date as Month day, year hours:minutes:seconds.<br />

For example, var twoThousandFifteen = new Date("December 31, 2015<br />

23:59:59");. If you omit hours, minutes, or seconds, the value will be set<br />

to 0.<br />

• A set of integer values for the year, month, and day. For example, var<br />

christmas = new Date(2015, 11, 25);.<br />

• A set of integer values for the year, month, day, hour, minute, and seconds.<br />

For example, var christmas = new Date(2015, 11, 25, 21, 00, 0);.<br />

[ 15 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!