Section 4: Objects and Functions Flashcards
What are objects in javascript?
Collections of name/value pairs sitting in memory. They can contain numbers, methods (functions), etc.
What can objects contain?
- Primitive “property” 2. Object “property” 3. Function “method” (still a function but connected to an object so it’s called a method. An object sits in memory and has other things sitting in memory connected to it.
What is the new object syntax?
var person = new Object(); (note: This is not the best way to create an object)
Computed member access operator
objectName[] (operator is the brackets. Inside brackets is a property or method name. Inside brackets you insert the value of the name you’re trying to access in memory.)
What does this log to the console? var person = new Object(); person[“firstname”] = “Tony”; var firstNameProperty = “firstname”; console.log(person); console.log(person[firstNameProperty]);
Tony
What is the easier/clearer was to access operators than the CMAO? (computed member access operator)
. operator (spoken “dot operator”)
e.g. console.log(person.firstname);
>> the dot operator takes two parameters, object before the dot and the name of the value you’re looking for after the dot.
What is the dot operator also called?
Member access operator
How do you use a dot operator to add properties to a sub/child object?
Example (note: left associativity!):
person. address = new Object();
person. address.street = “111 Main St.”;
person. address.city = “New York”;
person. address.state = “NY”;
What does the following look like with dot operators in place of computer member access operators?
console.log(person[“address”][“state”]);
console.log(person.address.state);
These offer the same results yet the preferred method is using the dot operator unless you really need to access properties using some kind of dynamic string.
What is an object literal?
var person = {};
The above is a shorthand and the same as new Object(); When the browser comes across a curly brace it assumes you’re creating an object.
Insert properties firstname and lastname into object person using object literal notation.
var person = { firstname: ‘Tony’, lastname: ‘Alicea’ };
Also, as a more readable version:
var person = {
firstname: ‘Tony’,
lastname: ‘Alicea’,
address: {
street: ‘111 Main St.’,
city: ‘New York’,
state: ‘NY’
}
};
Create an object on the fly with function greet and names firstname and lastname.
greet({
firstname: ‘Mary’,
lastname: ‘Doe’
});
note: you can create an object wherever you want and you can use it whenever you use any variable.
Define namespace
A container for variables and functions
Typically to keep variables and functions with the same name separate
NOTE: Javascript doesn’t have namespaces. Because of the nature of objects, we don’t need namespaces as a feature.
Primitive values don’t have any ___ or ___
properties or methods