Advanced JavaScript: Object Construction and Built-in Constructors
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.
- Prefer literal syntax over
Object()constructor for object creation. Object.assign()copies properties from one or more source objects to a target object.Object.keys()retrieves all enumerable property names of an object.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:
forEach()iterates over each element, replacing traditionalforloops.filter()generates a new array containing elements that pass a test.map()creates a new array by transforming each element.join()concatenates all elements into a string.find()returns the first element matching a condition; otherwise,undefined.every()checks if every element passes a test; returnstrueif so.some()checks if at least one element satisfies a condition.concat()merges two or more arrays into a new one.sort()sorts elements in place.splice()modifies an array by removing or replacing eelments.reverse()reverses the order of elements in an array.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:
lengthreturns the number of characters in a string.split(separator)splits a string into an array of substrings.substring(start, end)extracts part of a string between indices.startsWith(searchString, position)determines whether a string begins with the specified characters.includes(searchString, position)checks if a string includes another string.toUpperCase()converts a string to uppercase.toLowerCase()converts a string to lowercase.indexOf(searchValue)finds the index of the first occurrence of a substring.endsWith(searchString, length)checks if a string ends with a specific substring.replace(searchValue, newValue)replaces occurrences of a pattern in a string.match(regexp)searches for matches in a string using a regular expression.