JavaScript Introducing ES2015 The Cooler Parts of ES2015 Arrow Functions

Marcus Schumacher
Marcus Schumacher
12,185 Points

Can someone explain line 8?

How the getKeys function of Person is return Object.keys(this);

How does the keys method of Object know what to return when provided with 'this' as a parameter?

1 Answer

Steven Parker
Steven Parker
173,991 Points

When the "getkeys" method is invoked on an object (of type Person), the value of "this" is a reference to the current object instance. So when you pass it to "Object.keys", it returns the keys in the current object.

But as demonstrated in the video, if the function is invoked from a different context, "this" might not refer to an object at all and an error could occur. But the video goes on to fix this by using an arrow function. After that "this" refers to the object again.

You might enjoy the short workshop Understanding "this" in JavaScript.