Lesson 14
Objects
Most of the JavaScript data types you have looked at so far have held simple atomic values such as strings or numbers. This lesson looks at objects: Objects encapsulate multiple data properties, along with a set of methods capable of operating on these properties.
Objects are potentially the most difficult aspect of JavaScript for programmers migrating from other languages because objects in JavaScript work in a fundamentally different way than most other languages. As you will see, this is not a bad thing, but if you don't understand these fundamental differences, you will struggle to write complex web applications.
Object Literals
Objects can be created in JavaScript by enclosing a set of properties and methods within a pair of curly brackets. The following is an example of an object with two properties and one method:
> o = {
firstName:'Dane',
lastName:'Cameron',
getFullName: function() {
return this.firstName + ' ' + this.lastName;
}
}
In this case, the two properties are firstName
and lastName
. These properties are both strings, but they could be any data type: numbers, Booleans, arrays, or other objects.
Notice that the property names are separated from their values with colons, and the properties are separated from one another with commas.
It is possible to access these properties in two different ways:
> o.firstName
"Dane"
> o['firstName']
"Dane"
These two mechanisms are not exactly equivalent. The second mechanism (with the square brackets) will ...
Get HTML5, JavaScript, and jQuery 24-Hour Trainer now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.