Beginning AngularJS

(WallPaper) #1

ChApter 1 ■ JAvASCrIpt You Need to KNow


Adding Methods to Objects

We looked at functions earlier, and now we are going to look at methods. Here’s the good news: methods and
functions are so similar, you are already most of the way there. Let’s look at the example shown in Listing 1-20.


Listing 1-20. An Object with a Method


<!DOCTYPE html>




JavaScript Primer





If you look through Listing 1-20, you will see that it isn’t really anything special, until you get to the myInfo
property. This property has a value just like any other property, but it just so happens to be a function. The last line
shows it being called through the object reference.
A function attached to an object in this manner is known as a method. Why is that? The short and simple answer
is that, in reality, they are subtly different things, both in how JavaScript treats them and how you, as a developer, are
supposed to use them.
Did you notice that inside the myInfo method we refer to name as this.name? Using the special this keyword, you
get access to other properties of the same object. Essentially, this is a reference to the current object. (Some of you
may be familiar with other languages in which something like this exists under the guise of Me or self.) Here is the
output:


My name is Andrew.
My age is 21.


I want to make a minor change to the preceding listing. Here is a snippet of the affected area, the myInfo method:

myInfo: function () {
console.log("My name is " + firstName + ". ");
console.log("My age is " + age + ".");
}

Free download pdf