User-Defined Objects
Everything in JavaScript is either one of the five primitive values (strings, numbers, Booleans, undefined, and null) or an object.
Objects are JavaScript’s sixth and final type.
In addition to built-in objects (arrays, strings, functions, document, Math, Date, RegExp, …), new objects can be quickly and easily defined by the user.
Definitions
An object in JavaScript is a collection of properties.
A property name is a JavaScript identifier or a string literal.
Quotes around a property name are optional if the name would be a legal JavaScript name. So quotes are required around “first-name”, but are optional around first_name.
Property values can be any JavaScript value: strings, numbers, Booleans, arrays, functions, objects and so on.
If a property’s value is a function, it is known as a method.
Objects as Associative Arrays
In computing, an associative array is a data structure that maps keys to values.
Therefore, an associative array (a.k.a. hash table, hash map, symbol table, dictionary, or db record) is a data structure composed of a collection of {key: value} pairs.
Object Literals
The easiest way to create an object is with an object literal.
An object literal is a comma-separated list of colon-separated name:value pairs, enclosed within curly braces {}.
Object literals are a distinguishing feature of the JavaScript language, as they allow objects to be created quickly without the need to define a class (as one has to do in Python, Java, C++, C#, etc.).
Example 1 (p. 112)
var superman = { name: "Superman", "real name": "Clark Kent", height: 75, weight: 235, hero: true, villain: false, allies: ["Batman","Supergirl","Superboy"], fly: function(){ return "Up, up and away!"; } }; Exercise: Add a getRealName method that returns Superman's real name.
Example 2
var lotteryNumbers = [4, 8, 15, 16, 23, 42]; var profile = { firstName: "Hugo", lastName: "Reyes", flight: "Oceanic 815", car: "Camaro" }; console.log(profile.lastName[0]); //"R"
Note how the lotteryNumbers array lends itself well to storing the sequence of lottery numbers, while the profile object is perfect for storing the key/value pairs of a person’s (Hugo’s) profile.
Example 3
- Dice.js (Github)
this Keyword As an Object Method
When a function is called as a method of an object, its this
is set to the object the method is called on.
In the following example, when o.f()
is invoked, inside the function this
is bound to the o
object.
var o = {
prop: 37,
f: function() {
return this.prop;
}
};
console.log(o.f()); // logs 37
Optional
- Data Structures: Objects and Arrays (Eloquent JavaScript)
- Object Methods (Eloquent JavaScript)
- What it really means when people say “Everything in JavaScript is an object”. (OReilly video, 7-min.).