Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Methods Chaining in Javascript

I'm new to ES6 and Javascript and I can't figure out what's wrong with chaining this dump() method in the following piece of code.

It returns "main.js:25 Uncaught TypeError: Cannot read property 'dump' of undefined":

class TaskCollection {

constructor(tasks = []) {
    this.tasks = tasks;
}

addTasks(newTasks = []) {
    this.tasks = this.tasks.concat(newTasks);
}

dump() {
    console.log(this.tasks);
}

}

let myTasks = new TaskCollection([
        'Do stuff'
]);

myTasks.addTasks([
    'New Task'
]).dump();

Now if I don't chain that dump() method, everything would work just fine.

myTasks.addTasks([
'New Task'
]);

myTasks.dump();
like image 438
BehnUm Avatar asked Jan 06 '23 17:01

BehnUm


1 Answers

Method addTasks is not returning a reference to the object. If you want chaining to work, your method needs to look like this:

addTasks(newTasks = []) {
    this.tasks = this.tasks.concat(newTasks);

    return this;
}
like image 196
Mjh Avatar answered Jan 08 '23 06:01

Mjh