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 trial

JavaScript Introducing ES2015 The Cooler Parts of ES2015 Arrow Functions

Jiho Song
Jiho Song
16,469 Points

Why First example of this video didnt return the intened results?

'use strict';

var Person = function (data) { for (var key in data) { this[key] = data[key];
} this.getKeys = function () { return Object.keys(this); } }

var Alena = new Person({ name: 'Alena', role: 'Teacher' });

console.log('Alena\'s Keys:', Alena.getKeys()); // 'this' refers to 'Alena'

var getKeys = Alena.getKeys;

console.log(getKeys()); // 'this' refers to the node process

this seems to be working well but it shows me error like in the video

But at what point error was corrected by changing only to arrow functions?

aren't both function supposed to be working in the exact same way?

I'm bit confused..

1 Answer

Erin Condon
Erin Condon
5,938 Points

I recommend checking this article out: https://medium.freecodecamp.com/learn-es6-the-dope-way-part-ii-arrow-functions-and-the-this-keyword-381ac7a32881#.9os9fiyx9

The above article goes into further detail about how/when/why the scope of 'this' is being lost and how/why the arrow function fixes it. There are also a lot more examples that help illustrate what's happening.

Hope it helps!

Jiho Song
Jiho Song
16,469 Points

Thanks lot of help

Yea i am glad you posted this it made the most sense out of any thing. Would have spent way to long trying to understand why the code was doing what it was doing before arrow functions.