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.

pretty handy when you need more than two or three objects that possess the same<br />

properties, but with different values. Come to think of it, this is exactly what <strong>JavaScript</strong><br />

does with the native objects. The Person() constructor follows the same principles as<br />

the Array() constructor. So new Array('foo','bar') is really not that different than<br />

new Person(true, 33, 'male'). Creating your own constructor functions is just<br />

using the same pattern that <strong>JavaScript</strong> itself uses for its own native constructor<br />

functions.<br />

Notes<br />

It is not required, but when creating custom constructor functions intended to be used<br />

with the new operator, it’s best practice to make the first character of the constructor<br />

name uppercase: Person() rather than person().<br />

One tricky thing about constructor functions is the use of the this value inside of the<br />

function. Remember, a constructor function is just a cookie cutter. When used with the<br />

new keyword, it will create an object with properties and values defined inside of the<br />

constructor function. When new is used, the value this literally means the new object or<br />

instance that will be created based on the statements inside the constructor function.<br />

On the other hand, if you create a constructor function and call it without the use of the<br />

new keyword, the this value will refer to the "parent" object that contains the function.<br />

More detail about this topic can be found in Chapter 6.<br />

It's possible to forgo the use of the new keyword and the concept of a constructor<br />

function by explicitly having the function return an object. The function would have to be<br />

written explicitly to build an Object() object and return it: var myFunction =<br />

function() {return {prop: val}};.<br />

Instantiating constructors using the new operator<br />

A constructor function is basically a cookie-cutter template used to create preconfigured<br />

objects. Take String() for example. This function, when used with the new<br />

operator (new String('foo')), creates a string instance based on the String()<br />

"template.” Let's look at an example.<br />

Sample: sample9.html<br />

<br />

var myString = new String('foo');<br />

console.log(myString); // Logs foo {0 = "f", 1 = "o", 2 = "o"}<br />

<br />

25

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

Saved successfully!

Ooh no, something went wrong!