Java Reference
In-Depth Information
Save this page as ch5_example8.html . When you load the page into a web browser, it displays the
message: "Hello, Jane Doe. I'm John Doe" .
First, this code creates a function called createPerson() that accepts a person's first and last names as
parameters. This function creates an object with the person's first and last names using object literal notation:
function createPerson(firstName, lastName) {
return {
The first property created is the firstName property, and it is assigned the value of the firstName
parameter:
firstName: firstName,
Next is the lastName property, which receives its value from the createPerson() function's lastName
parameter:
lastName: lastName,
Then a method called getFullName() is created. Its purpose is to return the first and last name of the
person to the caller:
getFullName: function() {
return this.firstName + " " + this.lastName
},
This method uses the this variable to access this object's firstName and lastName properties. Note
that the this variable is the only way to retrieve these properties—the object doesn't have a name; it is
an anonymous object that is created and then returned to the caller.
The final method of this object is greet() . It accepts another person object as a parameter and uses its
getFullName() in order to greet that person:
greet: function(person) {
alert("Hello, " + person.getFullName() +
". I'm " + this.getFullName());
}
};
}
The next two lines create two objects two represent two individual people:
var johnDoe = createPerson("John", "Doe");
var janeDoe = createPerson("Jane", "Doe");
Notice the absence of the new keyword. The createPerson() function is not a constructor function (you
learn how to write constructor functions later). It's simply a function that creates and returns an object.
Finally, John Doe greets Jane Doe by calling the greet() method and passing the janeDoe object to it:
johnDoe.greet(janeDoe);
Search WWH ::




Custom Search