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

olu adesina
olu adesina
23,007 Points

Im a bit lost HELP!!!

I've run this through google chrome debugger step by step and is do not understand the why Alena object is used as a argument in the person function as person is never called like this ..... Person(Alena); all so if some one could explain this[key] = data[key]

'use strict';

var Person = function (data) {
    for (var key in data) {
        this[key] = data[key];
    }
    this.getKeys = () => {
        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

1 Answer

Steven Parker
Steven Parker
231,261 Points

Person is a constructor function. The capital first letter is a convention used to indicate it's that kind of function.

Constructors are used to create new instances of a class object. That is happening on this line:

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

The function is called, along with the "new" keyword, to create a new instance of the "Person" class and assign it to "Alena". The argument is an object itself which contains the properties "name" and "role".

Inside a constructor, "this" refers to the object being created, so here it would be "Alena". The line that has "this[key] = data[key];" is copying all the properties from the argument object that was passed in (data) and putting them into the current object (Alena). So when the loop finishes, Alena.name will be 'Alena', and Alena.role will be 'Teacher'.

Does that clear it up?

olu adesina
olu adesina
23,007 Points

oh OK i get it now the loop within the constructor allows us to create a person object with an unlimited amount keys the last thing i am struggling with is object.keys(this) what does the object refer to.

Steven Parker
Steven Parker
231,261 Points

"Object" is the system's "generic object", and Object.keys is a function that returns all the property names of an object. And since "this" is the current (Person) object, what's happening here is that a "getKeys" method is being defined that just calls "Object.keys" for you on this Person.