Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialde forbe
76 PointsObject prototype not supporting arrow function
I am working on Linked List in JavaScript. When I add prototype to my Link List Object with arrow function it doesn't work but when I do the same task with normal function It works fine. This is my code:
function LinkedList() {
this.head = null;
this.tail = null;
}
function Node(value, head, tail) {
this.value = value;
this.head = head;
this.tail = tail;
}
LinkedList.prototype.addToHead = function(value) {
node = new Node(value, this.head, null);
if (this.head) this.head.tail = node;
else this.tail = node;
this.head = node;
}
// LinkedList.prototype.addToHead = value => {
// node = new Node(value, this.head, null);
// if (this.head) this.head.tail = node;
// else this.tail = node;
// this.head = node;
// }
const list = new LinkedList();
list.addToHead(100)
console.dir(list)
Output with normal function:
LinkedList {
head: Node { value: 100, head: null, tail: null },
tail: Node { value: 100, head: null, tail: null } }
Output when i un-comment that arrow functioned code and comment that normal functioned code:
LinkedList { head: null, tail: null }
1 Answer
Amber Cyr
19,699 Pointsunfortunately, you can not use the arrow syntax in some instances, prototype declaration being one of them. This is because arrow functions will bind to the context you declared it in. This case it is binding to the value within your LinkedList.prototype.addToHead and not creating the .addToHead method. I have also provided a link that may be helpful to you as well.
de forbe
76 Pointsde forbe
76 PointsThanks for your help mam.