简体   繁体   English

理解Javascript中的链接方法

[英]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. 我是ES6和Javascript的新手,我无法弄清楚在下面的代码中链接这个dump()方法有什么问题。

It returns " main.js:25 Uncaught TypeError: Cannot read property 'dump' of undefined ": 它返回“ main.js:25 Uncaught TypeError:无法读取未定义的属性'dump' ”:

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. 现在,如果我不链接dump()方法,一切都会正常工作。

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

myTasks.dump();

Method addTasks is not returning a reference to the object. 方法addTasks不返回对象的引用。 If you want chaining to work, your method needs to look like this: 如果你想链接工作,你的方法需要如下所示:

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

    return this;
}

In order to use method chaining, you need to return this from the earlier method. 要使用方法链接,您需要从早期方法返回this 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. 在您的情况下,您不会从addTasks返回this addTasks ,因此调用addTasks的结果是undefined ,并且您无法在undefined.上调用方法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 ). 这取决于如何addTasks写,你可能会调用dump在同一个对象(方法链接),或在完全一些其他的对象(如果addTasks返回比其他东西this )。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM