Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

JavaScript Objects Fundamentals and Creation Patterns

Tech 2

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:

  1. Constructor funcsions follow capitalization convention for first letter.
  2. Properties and methods inside functions require this prefix, indicating current object's attributes and methods.
  3. Constructor functions don't require return statements.
  4. When creating objects, new keyword 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 with new keyword is called object instantiation

The new Keyword

When executing new, four actions occur:

  1. Creates a new empty object in memory.
  2. Sets this to reference this new object.
  3. Executes code inside constructor function, adding properties and methods to the new object.
  4. 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

  1. Objects provide clearer code structure
  2. Objects represent complex data type object
  3. Essence: Objects are collections of unordered related properties and methods
  4. Constructor functions refer to broad categories, like apples - whether red or green, all called apples
  5. Object instances specify particular entities, like this specific apple, or a specific instructor
  6. for...in statement iterates through object properties
Tags: javascript

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.