Lecture-6 Notes - OOP in JS-3310
Lecture-6 Notes - OOP in JS-3310
Objects
Brief Recap:
● In Lecture 3, we briefly introduced objects and discussed object creation using
literals and accessing objects using dot and bracket notation.
● In this session, we will explore objects in more detail, focusing on their
properties, methods, and additional concepts.
Introduction to Objects:
● In JavaScript, objects are composite data types used to represent real-world
entities or concepts.
● Objects are containers that store related data and functions together as
properties and methods.
● Objects can be instantiated using two different approaches: object literals or
constructor functions. In the following sections of the notes, we will delve
deeper into the concept of constructor functions and discuss their usage in
creating and initializing objects.
Example:
● In ES5 object literals, methods are defined similarly to other properties. The
function expressions are used to assign values to these properties.
For instance:
var obj = {
calculateArea: function (radius) {
return Math.PI * radius * radius;
},
displayMessage: function (name) {
console.log("Hello, " + name + "!");
}
};
In the code above, the `obj` object has two methods: `calculateArea` and
`displayMessage`. The `calculateArea` method calculates the area of a circle
based on the given radius, while the `displayMessage` method logs a personalized
greeting to the console.
With the ES6 method definitions, we can directly define methods within the object
literal without using the `function` keyword. The functionality remains the same as
in the previous example.
Example:
Example:
● Both dot notation and bracket notation achieve the same result of accessing
object properties.
● Dot notation is commonly used when the property name is known and valid as
an identifier.
● Bracket notation is more versatile as it allows using variables or property
names with special characters or spaces.
● Bracket notation is also used when the property name is dynamically
determined.
It's important to note that dot notation and bracket notation are interchangeable, but
bracket notation provides more flexibility in certain situations.
`this` keyword
● In lecture 5, we discussed the keyword 'this' in JavaScript and its general
purpose. Now, let's delve deeper into the concept of 'this' specifically in the
context of JavaScript objects.
● In this section, we will provide a comprehensive explanation of 'this' in
object-oriented programming, highlighting its significance and providing clear
examples.
● When used within an object method, 'this' refers to the object itself.
● This allows seamless access to other properties and methods of the same
object.
Let's illustrate this concept with an example:
const person = {
name: 'Peter',
age: 30,
greet: function() {
console.log('Hello, my name is ' + this.name + ' and I am ' +
this.age + ' years old.');
}
};
Here, 'this' within the 'greet' function allows for dynamic access to object
properties, ensuring that the function can be applied to different objects while
maintaining the correct context.
Constructor Functions
● When creating objects in JavaScript, object literals serve as a convenient and
straightforward approach.
● However, there are scenarios where object literals may not be suitable or
efficient for object creation. This leads us to the introduction of constructor
functions, which provide a powerful alternative for creating and initializing
objects.
● Object literals have their limitations when creating multiple objects with similar
properties and behaviors. Each object created with an object literal has its
own properties and methods, resulting in duplicated code and inefficiency.
● Constructor functions address this limitation by providing a blueprint for
creating multiple objects with shared properties and methods.
● By defining a constructor function, we can instantiate new objects that inherit
properties and methods from the constructor's prototype.
● This approach promotes code reusability, reduces redundancy, and enables
efficient object creation.
Syntax:
1. Inside the constructor function, the 'this' keyword refers to the object being
created.
2. 'this' allows access to and assignment of object properties within the function.
B. Assigning Properties:
Example:
Understanding constructor functions allows for efficient code organization and the
creation of reusable object templates.
Prototype
Example:
function Person(name) {
this.name = name;
}
var bob = new Person('Bob');
console.log(Object.getPrototypeOf(bob)); // returns Person {}
Prototypal Inheritance
Prototypal inheritance refers to how objects inherit from their prototypes. When you
look up a property on an object (e.g., `bob.name`), if it doesn't exist on the object
itself, JavaScript looks at its prototype chain until it finds what it needs.
Example:
function Animal() {}
Animal.prototype.move = function() { console.log('moving') };
function Dog() {}
Dog.prototype.bark = function() { console.log('woof!') };
Dog.prototype.__proto__ = Animal.prototype;
Prototype in Array
Arrays in JavaScript are also objects, and therefore have a prototype. The
`Array.prototype` object contains properties and methods that are available to all
arrays created from the `Array` constructor function.
Example:
Here we've used the `.map()` method of our array instance to return a new array
with each element doubled. This method is actually defined on the
`Array.prototype`, so when we call it on our specific instance (`myArr`), JS looks
up its prototype chain to find where `.map()` is defined (in this case:
`Array.prototype`).
Object.create
● In JavaScript, the `Object.create()` method is used to link objects
together and establish prototype chains. It allows us to create a new object
with a specified prototype object.
● The `Object.create()` method creates a new object and sets the specified
object as its prototype.
● It provides a way to create objects that inherit properties and methods from a
prototype object.
Example:
const personPrototype = {
greet: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
const john = Object.create(personPrototype);
john.name = "John";
john.greet(); // Output: Hello, my name is John.
call/apply/bind methods
● In JavaScript, the `call()`, `apply()`, and `bind()` methods are used
to manipulate the execution context of functions and explicitly set the value of
`this`. These methods provide flexibility and control over how functions are
invoked.
● The `call()` method is used to invoke a function and explicitly set the value
of `this`.
● It accepts arguments individually, separated by commas.
Example:
function greet(name) {
console.log(`Hello, ${name}! I'm ${this.title}.`);
}
const person = {
title: "Mr."
};
greet.call(person, "John"); // Output: Hello, John! I'm Mr.
2. The `apply()`Method:
Example:
function greet(name) {
console.log(`Hello, ${name}! I'm ${this.title}.`);
}
const person = {
title: "Mr."
};
greet.apply(person, ["John"]); // Output: Hello, John! I'm Mr.
● The `bind()` method creates a new function that has a specified `this`
value and, optionally, initial arguments.
● It does not immediately invoke the function but instead returns a new function
that can be called later.
Example:
function greet(name) {
console.log(`Hello, ${name}! I'm ${this.title}.`);
}
const person = {
title: "Mr."
};
const greetPerson = greet.bind(person);
greetPerson("John"); // Output: Hello, John! I'm Mr.
Object and Array Destructuring
Object Destructuring:
In JavaScript, object destructuring is a convenient way to extract values from an
object and assign them to variables. It allows you to access and unpack properties
from an object in a concise and structured manner.
Syntax:
Example 1:
const { x, y } = { x: 11, y: 8 }; // x = 11; y = 8
const { x: x, y: y } = { x: 11, y: 8 };
Example 2:
You can combine property value shorthand with default values:
const { x, y = 1 } = {}; // x = undefined; y = 1
Array Destructuring
Similarly, array destructuring in JavaScript provides a concise way to extract values
from an array and assign them to variables.
Syntax:
2. Ignoring Elements: You can skip elements in the array by leaving empty
slots (commas) in the destructuring pattern.
3. Rest Syntax: The rest syntax (...) allows you to capture the remaining
elements of an array into a new array.
const [p = 0, q = 0, r = 0] = numbers;
console.log(p); // Output: 1
console.log(q); // Output: 2
console.log(r); // Output: 3
Object and array destructuring are powerful features in JavaScript that simplify the
extraction of values from objects and arrays, providing cleaner and more readable
code.
Summarizing it
In this lecture, we have covered the following topics:
● The "this" Keyword in Objects: We learned that "this" refers to the object itself
when used within an object method, allowing seamless access to other
properties and methods of the same object.
References
● Object Prototypes: Link
● Array Prototype: Link