Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Advanced JavaScript: Object Construction and Built-in Constructors

Tech 1

Object Construction

Constructor Functions

A constructor function serves as a blueprint for creating objects.

<script>
// Constructor function - note the capitalized first letter
function User(name, age, hobby) {
    this.name = name;
    this.age = age;
}

// Instantiating an object using the new keyword
const user1 = new User("Alice", 25);
console.log(user1);
</script>

Using the new operator to invoke a function is referred to as instantiation.

Instance Members

Objects created through a constructor function are known as instance objects. Properties and methods defined within these instances are termed instance members.

<script>
  // Constructor function
  function Student() {
    // Inside the constructor, 'this' refers to the instance
    // Dynamically adding properties
    this.name = 'Bob';
    // Dynamically adding methods
    this.greet = function () {
      console.log('Hello everyone!');
    };
  }

  // Creating an instance
  const student1 = new Student();
  console.log(student1);
  console.log(student1.name); // Accessing instance property
  student1.greet(); // Invoking instance method
</script>

The this inside the constructor points to the resulting instance. Any properties or methods added dynamically to it become instance members.

Static Members

Static members refer to properties and methods attached directly to the constructor function itself. In static methods, this refers to the constructor function.

<script>
  // Constructor function
  function Student(name, age) {
    // Omitting instance-specific members
  }

  // Adding static properties
  Student.eyeCount = 2;
  Student.armCount = 2;

  // Adding static method
  Student.walk = function () {
    console.log('Everyone can walk...');
    // 'this' now refers to the Student constructor
    console.log(this.eyeCount);
  };
</script>

Built-in Constructors

JavaScript recognizes six primitive data types: string, number, boolean, undefined, null, and object. Internally, these primitives are wrapped into objects.

Object Constructor

Object is a built-in constructor used for creating plain objects.

  1. Prefer literal syntax over Object() constructor for object creation.
  2. Object.assign() copies properties from one or more source objects to a target object.
  3. Object.keys() retrieves all enumerable property names of an object.
  4. Object.values() returns an array of an object's own enumerable property values.

Array Constructor

Array is a built-in constructor used for creating arrays.

<script>
  // Using constructor to create an array
  let arr = new Array(5, 7, 8);
  
  // Using literal syntax to create an array
  let list = ['HTML', 'CSS', 'JavaScript'];
</script>

After assigning arrays, modifying one will affect the other if they reference the same object.

Common Methods:

  1. forEach() iterates over each element, replacing traditional for loops.
  2. filter() generates a new array containing elements that pass a test.
  3. map() creates a new array by transforming each element.
  4. join() concatenates all elements into a string.
  5. find() returns the first element matching a condition; otherwise, undefined.
  6. every() checks if every element passes a test; returns true if so.
  7. some() checks if at least one element satisfies a condition.
  8. concat() merges two or more arrays into a new one.
  9. sort() sorts elements in place.
  10. splice() modifies an array by removing or replacing eelments.
  11. reverse() reverses the order of elements in an array.
  12. findIndex() returns the index of the first element matching a condition.

String Constructor

String is a built-in constructor for creating strings.

<script>
  // Creating a string via constructor
  let str = new String('Hello World!');
  
  // Creating a string via literal syntax
  let str2 = 'Hello, World!';
</script>

Common Methods:

  1. length returns the number of characters in a string.
  2. split(separator) splits a string into an array of substrings.
  3. substring(start, end) extracts part of a string between indices.
  4. startsWith(searchString, position) determines whether a string begins with the specified characters.
  5. includes(searchString, position) checks if a string includes another string.
  6. toUpperCase() converts a string to uppercase.
  7. toLowerCase() converts a string to lowercase.
  8. indexOf(searchValue) finds the index of the first occurrence of a substring.
  9. endsWith(searchString, length) checks if a string ends with a specific substring.
  10. replace(searchValue, newValue) replaces occurrences of a pattern in a string.
  11. match(regexp) searches for matches in a string using a regular expression.

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.