this in objects in Javascript - Time & Space Complexity
Let's explore how the time it takes to run code involving this in objects changes as the input grows.
We want to know how the program's speed changes when using this inside object methods.
Analyze the time complexity of the following code snippet.
const obj = {
values: [1, 2, 3, 4, 5],
sum() {
let total = 0;
for (let num of this.values) {
total += num;
}
return total;
}
};
obj.sum();
This code sums all numbers stored in the object's values array using this to access the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the
valuesarray inside thesummethod. - How many times: Once for each number in the array, so as many times as the array length.
As the number of items in values grows, the loop runs more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items; double the items means double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items in the array.
[X] Wrong: "Using this inside the method makes the code slower or more complex."
[OK] Correct: Accessing this is just a reference to the object and does not add extra loops or slow down the code beyond the loop itself.
Understanding how this works inside objects helps you write clear and efficient methods, a skill useful in many coding tasks and interviews.
"What if the values property was another object instead of an array? How would the time complexity change?"
Practice
this refer to inside a regular method of an object in JavaScript?Solution
Step 1: Understand
Inside a regular function defined as a method of an object,thisin object methodsthisrefers to the object that owns the method.Step 2: Compare with other contexts
Unlike arrow functions or global functions, regular methods bindthisto the object itself.Final Answer:
The object itself -> Option AQuick Check:
thisin object method = object [OK]
this as the object [OK]- Thinking
thisis always global - Confusing arrow functions with regular functions
- Assuming
thisis the method name
this inside an object?Solution
Step 1: Identify correct method syntax
const obj = { greet() { console.log(this.name); } }; uses the concise method syntax with a regular function, which correctly bindsthisto the object.Step 2: Check other options for errors
const obj = { greet: () => console.log(this.name) }; uses an arrow function, which does not bindthisto the object. Options B and D have invalid syntax for function definitions.Final Answer:
const obj = { greet() { console.log(this.name); } }; -> Option CQuick Check:
Regular method syntax = const obj = { greet() { console.log(this.name); } }; [OK]
- Using arrow functions for methods
- Incorrect function syntax inside objects
- Confusing method shorthand with arrow functions
const person = {
name: 'Alice',
greet() {
console.log(this.name);
}
};
person.greet();Solution
Step 1: Identify
The methodthisinside greet methodgreetis a regular function inside thepersonobject, sothisrefers toperson.Step 2: Access the
Sincenamepropertythisisperson,this.nameis 'Alice'. The console logs 'Alice'.Final Answer:
Alice -> Option AQuick Check:
this.name= 'Alice' [OK]
this points to the object [OK]- Expecting undefined because of arrow function confusion
- Thinking
thisis global - Assuming method returns error
const car = {
brand: 'Toyota',
showBrand: () => {
console.log(this.brand);
}
};
car.showBrand();Solution
Step 1: Identify arrow function issue
Arrow functions do not have their ownthis. Here,this.brandis undefined becausethisis not bound tocar.Step 2: Fix by using regular function
ChangingshowBrandto a regular method bindsthistocar, sothis.brandcorrectly accesses 'Toyota'.Final Answer:
Change arrow function to regular function: showBrand() { console.log(this.brand); } -> Option DQuick Check:
Regular function bindsthiscorrectly [OK]
this [OK]- Using arrow functions for methods
- Trying to bind
thison arrow functions - Ignoring
thiscontext rules
name. Which code correctly uses this to achieve this?const user = {
name: 'Bob',
greet: ???
};
console.log(user.greet());Solution
Step 1: Check method syntax and
greet() { return `Hello, ${this.name}!`; } uses a regular method syntax, sothisbindingthiscorrectly refers to theuserobject.Step 2: Validate other options
greet: () => `Hello, ${this.name}!` uses an arrow function, which does not bindthisto theuserobject. Options B and C have invalid syntax for function definitions.Final Answer:
greet() { return `Hello, ${this.name}!`; } -> Option BQuick Check:
Regular method withthis= greet() { return `Hello, ${this.name}!`; } [OK]
this access in objects [OK]- Using arrow functions for methods
- Incorrect function syntax
- Expecting
thisto work in arrow functions
Ready to prove it?
Pass the test and this pattern moves unknown
