17.11.2015 Views

JavaScript_Succinctly

Create successful ePaper yourself

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

Date() constructor function is a cookie cutter for date objects. That is, it produces date<br />

objects from a default pattern defined by the Date() constructor function.<br />

At this point, you should be well acquainted with creating object instances from native<br />

constructor functions (e.g., new String('foo')) and user-defined constructor<br />

functions (e.g, new Person(true, 33, 'male')).<br />

Notes<br />

Keep in mind that Math is a static object—a container for other methods—and is not a<br />

constructor that uses the new operator.<br />

Creating shorthand or literal values from constructors<br />

<strong>JavaScript</strong> provides shortcuts—called "literals"—for manufacturing most of the native<br />

object values without having to use new Foo() or new Bar(). For the most part, the<br />

literal syntax accomplishes the same thing as using the new operator. The exceptions<br />

are: Number(), String(), and Boolean()—see the notes after the following sample.<br />

If you come from other programming backgrounds, you are likely more familiar with the<br />

literal way of creating objects. In the following sample, I instantiate the native <strong>JavaScript</strong><br />

constructors using the new operator and then create corresponding literal equivalents.<br />

Sample: sample11.html<br />

<br />

var myNumber = new Number(23); // An object.<br />

var myNumberLiteral = 23; // Primitive number value, not an object.<br />

var myString = new String('male'); // An object.<br />

var myStringLiteral = 'male'; // Primitive string value, not an object.<br />

var myBoolean = new Boolean(false); // An object.<br />

var myBooleanLiteral = false; // Primitive boolean value, not an object.<br />

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

var myObjectLiteral = {};<br />

var myArray = new Array('foo', 'bar');<br />

var myArrayLiteral = ['foo', 'bar'];<br />

var myFunction = new Function("x", "y", "return x*y");<br />

var myFunctionLiteral = function (x, y) { return x * y };<br />

var myRegExp = new RegExp('\bt[a-z]+\b');<br />

var myRegExpLiteral = /\bt[a-z]+\b/;<br />

27

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

Saved successfully!

Ooh no, something went wrong!