-2

I know this refers to the constructor method but what does the line this.tasks = tasks; do?

class TaskCollection {
    constructor(tasks =[]) {
        this.tasks = tasks;
    }
}
jonnystoten
  • 6,285
  • 2
  • 28
  • 36
lovetolearn
  • 95
  • 1
  • 4
  • 11
  • Perhaps this helps http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – elclanrs Jul 02 '16 at 11:00
  • `tasks` is only a parameter. `this.tasks` is an accessible object property. You can’t get `tasks` from outside the constructed object, but you can access it with `obj.tasks` if you set `this.tasks` first. – Sebastian Simon Jul 02 '16 at 11:04
  • "this" in the given context of a constructor actually refers to the class instance itself. Hence, through the use of "this" in the given context you can set the "task" properties of the instantiated objects of the class by passing in the necessary arguments to the constructor. – zubair1024 Jul 02 '16 at 11:06

2 Answers2

4

That line assigns the tasks passed in through the constructor to the "tasks" member of the class instance.

Basically, you can do this:

collection = new TaskCollection([task1,task2]);

Now, you can access those tasks like this:

collection.tasks // [task1,task2]
user1582024
  • 645
  • 5
  • 13
0

I don't think there is the reserved word Class in javascript, function TaskCollection here defines the class, this code works fine in a jsfiddle but needs to define what is the array tasks, and also define what is the constructor reserved word

function TaskCollection (name, tasks) {
        this.name = name;
        this.tasks = tasks;
}

var collection = new TaskCollection('col', ['task1','task2']);
console.log(collection.name);
nazimboudeffa
  • 809
  • 6
  • 19