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 trialVictor Ibasco
11,035 PointsJavaScript - Help me read and understand some of this code Please
https://gyazo.com/d21d15807de53f20732a01537a06350d
If the text gets reformatted, then the link above is a screen shot of the code. My questions: 1) the 'Person' was said to be a constructor. From what I understand, constructors instantiate an object--class / object literal with certain properties and behaviors. How is that a constructor because from what I know constructors are nested within a class. I'm not familiar with the syntax, can you point me to a resource on this ? 2) The for loop within the 'Person'. Can you point me to a resource explaining that syntax ' var key in data'. 3) For confirmation, the 'this' is referring to the instance of the Person object right ? I'm just bewildered by the syntax of the creation of the 'Person' and I don't know whether or not to treat it as an object or a class.
'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
1 Answer
Steven Parker
231,269 Points1. The class syntax where you have a method named "constructor" nested inside a class is a recent addition to JavaScript. The example shown here is the classic style where the constructor is created as a function that has the name of the class itself. This should be explained in the class you are taking.
2. The loop is a "for...in" type. Here's the MDN reference page for for...in.
3. The keyword "this" used in a constructor is a reference to the new object instance being created. There's a workshop here called Understanding "this" in JavaScript you may enjoy.
And "Person" in this example is a class (and also the name of the constructor function for that class). An example of an object would be "Alena".