Understanding Methods Chaining in Javascript

和自甴很熟 提交于 2019-12-22 08:39:47

问题


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

回答1:


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



回答2:


In order to use method chaining, you need to return this from the earlier method. In your case, you don't return this from addTasks, so the result of calling addTasks is undefined, and you can't call methods on undefined.

So just add

return this;

...to any method you want to be able to chain from.

Method chaining is not something special. When you do:

addTasks(/*...*/).dump();

what you're doing is effectively:

var x = addTasks(/*...*/);
x.dump();

...just without the variable. Depending on how addTasks is written, you might be calling dump on the same object (method chaining) or on some other object entirely (if addTasks returned something other than this).




回答3:


You should return this in *addTasks* method

    class TaskCollection {
        
        constructor(tasks = []) {
            this.tasks = tasks;
        }
        
        addTasks(newTasks = []) {
            this.tasks = this.tasks.concat(newTasks);
            return this;
        }
        
        dump() {
            console.log(this.tasks);
        }
        
        }
        
        let myTasks = new TaskCollection([
                'Do stuff'
        ]);
        
        myTasks.addTasks([
            'New Task'
        ]).dump();


来源:https://stackoverflow.com/questions/38368509/understanding-methods-chaining-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!