JavaScript Objects Fundamentals and Creation Patterns
Understanding Objects
Definition of Objects
In JavaScript, an object represents a collection of unordered related properties and methods. Everything in JavaScript can be considered an object, including strings, numbers, arrays, and functions.
Objects consist of two primary components:
- Properties: Represent the characteristics of an entity, expressed as attributes within the object (typically nouns)
- Methods: Represent the behavior of an entity, expressed as functions within the object (typically verbs)
Purpose of Objects
When storing single values, variables suffice. For multiple values (a group), arrays work well. However, consider storing complete personal information - using an array approach like:
var userData = ['John Doe', 'male', 35, 70];
Object-based representation provides clearer, more powerful structure:
johnDoe.name = 'John Doe';
johnDoe.gender = 'male';
johnDoe.age = 35;
johnDoe.weight = 70;
Alternative syntax:
individual.name = 'John Doe'; // Or individual['name'] = 'John Doe'
individual.gender = 'male';
individual.age = 35;
individual.weight = 70;
To remove specific elements:
// Delete specified property
delete targetObject[propertyKey]
Three Methods for Object Creation
JavaScript supports three primary approaches for creating objects:
- Using literal notation to create objects
- Using new Object() constructor
- Using constructor functions
Creating Objects with Literal Notation
Object literals: Curly braces {} contain properties and methods representing the specific entity.
Summary of Variables, Properties, Functions, and Methods
- Variables: Declared and assigned independently, exist separately
- Properties: Variables inside objects, no declaration needed, describe object characteristics
- Functions: Standalone entities, invoked via "functionName()"
- Methods: Functions inside objects, no declaration needed, invoked via "object.methodName()", describe object behavior and functionality
Creating Objects with new Object()
Follows the same principle as new Array()
Creating Objects with Constructor Functions
Constructor Functions: Special functions primarily used to initialize objects, assigning initial values to object member variables. They work together with the new operator. Common properties and methods can be extracted and encapsulated within these functions.
When using constructor functions in JavaScript, observe these points:
- Constructor functions create specific object types; their first letter should be capitalized
- Constructor functions must be used with new to be meaningful
function Musician(name, years, gender) {
this.fullName = name;
this.experience = years;
this.sex = gender;
this.perform = function (song) {
console.log(song);
}
}
var artist = new Musician('Andy Lau', 25, 'male'); // Function call returns an object
Important notes:
- Constructor funcsions follow capitalization convention for first letter.
- Properties and methods inside functions require
thisprefix, indicating current object's attributes and methods. - Constructor functions don't require
returnstatements. - When creating objects,
newkeyword must be used to invoke constructor functions.
Constructor Functions vs Objects
- Constructor functions, like
Musician(), abstract common parts of objects, encapsulating them in functions, referring to a broad category (class) - Created objects, like
new Musician(), specify particular instances; the process of creating objects withnewkeyword is called object instantiation
The new Keyword
When executing new, four actions occur:
- Creates a new empty object in memory.
- Sets
thisto reference this new object. - Executes code inside constructor function, adding properties and methods to the new object.
- Returns the new object (hence constructor functions don't need return statements).
Iterating Through Object Properties
The for...in statement iterates through array or object properties. Syntax:
for (identifier in objectName) {
// Execute code here
}
The identifier is custom-defined, following naming conventions, typically k or key.
for (var property in dataObject) {
console.log(property); // Here, property is the attribute name
console.log(dataObject[property]); // Here, dataObject[property] is the attribute value
}
Summary
- Objects provide clearer code structure
- Objects represent complex data type
object - Essence: Objects are collections of unordered related properties and methods
- Constructor functions refer to broad categories, like apples - whether red or green, all called apples
- Object instances specify particular entities, like this specific apple, or a specific instructor
for...instatement iterates through object properties