Search code examples
javascriptchaining

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();

Solution

  • 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;
    }