06.07.2017 Views

Mastering 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 2<br />

Next, we define an object with a testObj variable with a property named<br />

testObjFunc that receives a reference to testF()—don't fret if you are not really<br />

aware of object creation yet. By doing this, we created a testObjMethod() method.<br />

Now, when we invoke this method, we expect the function context to be displayed<br />

when we display the value of this.<br />

Invocation as a constructor<br />

Constructor functions are declared just like any other functions and there's nothing<br />

special about a function that's going to be used as a constructor. However, the way in<br />

which they are invoked is very different.<br />

To invoke the function as a constructor, we precede the function invocation with the<br />

new keyword. When this happens, this is bound to the new object.<br />

Before we discuss more, let's take a quick introduction to object orientation in<br />

<strong>JavaScript</strong>. We will, of course, discuss the topic in great detail in the next chapter.<br />

<strong>JavaScript</strong> is a prototypal inheritance language. This means that objects can inherit<br />

properties directly from other objects. The language is class-free. Functions that<br />

are designed to be called with the new prefix are called constructors. Usually, they<br />

are named using PascalCase as opposed to CamelCase for easier distinction. In<br />

the following example, notice that the greet function uses this to access the name<br />

property. The this parameter is bound to Person:<br />

var Person = function (name) {<br />

this.name = name;<br />

};<br />

Person.prototype.greet = function () {<br />

return this.name;<br />

};<br />

var albert = new Person('Albert Einstein');<br />

console.log(albert.greet());<br />

We will discuss this particular invocation method when we study objects in the next<br />

chapter.<br />

Invocation using apply() and call() methods<br />

We said earlier that <strong>JavaScript</strong> functions are objects. Like other objects, they also<br />

have certain methods. To invoke a function using its apply() method, we pass two<br />

parameters to apply(): the object to be used as the function context and an array<br />

of values to be used as the invocation arguments. The call() method is used in a<br />

similar manner, except that the arguments are passed directly in the argument list<br />

rather than as an array.<br />

[ 63 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!