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 trialAndrei Duhanes
14,155 PointsES2015 function shorthand notation in an Object dilemma!
Hey guys,
I have a question regarding the reference of the this key word in the following examples. Because in a course (not on treehouse) a veteran javascript developer explained that the this key word from the second example referees to the global object (like the ()=> does), but when trying it out, it looks like it refers to the object like a normal function declaration.
var test1 = {
testFunc: function() {
console.log(this);
}
};
test1.testFunc();
var test2 = {
testFunc() {
console.log(this);
}
};
test2.testFunc();
var test3 = {
testFunc: ()=> {
console.log(this);
}
};
test3.testFunc();
- Test1 - console.logs this to the Object
- Test2 - console.logs this to the Object ALSO ( but the instructor said this points to the Global obj like test 3)
- Test3 - console.logs to the global obj
My actual question is. Was that the case in ES2015 and they've changed it in ES2016 and maybe that course was old, or the instructor got it wrong although I doubt that.
1 Answer
Steven Parker
231,210 PointsIt sounds like you actually found an error in that other course.
Arrow functions don't establish a "this" like conventional functions do, which explains the difference in behavior of the third example. But since the second example is just a shorthand for the first, both establish a conventional function so "this" would be defined for the local object.