Java Reference
In-Depth Information
greet : function() {
alert("My name is " +
this.firstName + " " +
this.lastName;
}
};
Take a moment and study this code. First, notice this code uses curly braces to enclose the entire
object. Then notice that each property and method is defined by specifying the name of the
property/method, followed by a colon, and then its value. So, assigning the firstName property
looks like this:
firstName : "John"
There is no equal sign used here. In object literal notation, the colon sets the value of the property.
Finally, notice that each property and method definition is separated by a comma—very much like
how you separate individual elements in an array literal.
trY it out Using Object Literals
It is very important for you to understand object literals—they are used extremely liberally by
JavaScript developers. Let's look at an example that uses a function to create a custom object:
<!DOCTYPE html>
 
<html lang="en">
<head>
<title>Chapter 5, Example 8</title>
</head>
<body>
<script>
function createPerson(firstName, lastName) {
return {
firstName: firstName,
lastName: lastName,
getFullName: function() {
return this.firstName + " " + this.lastName
},
greet: function(person) {
alert("Hello, " + person.getFullName() +
". I'm " + this.getFullName());
}
};
}
 
var johnDoe = createPerson("John", "Doe");
var janeDoe = createPerson("Jane", "Doe");
 
johnDoe.greet(janeDoe);
</script>
</body>
</html>
Search WWH ::




Custom Search