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 trialAli .
15,521 Pointsdifferent between my code and course showing with "this"?
I just suggest. which one better?
// My code
const city = function(name, state){
this.name = name;
this.state = state;
this.mycity = () => {
console.log('My city is ' + this.name + ' ,and ' + this.state + ' is My state');
}};
city('Seattle', 'WA');
mycity()
/// course showing
var city = function(name, state){
this.name = name;
this.state = state;
this.mycity = function(){
console.log('My city is ' + this.name + ' ,and ' + this.state + ' is My state');
}};
locations = new city('Seattle', 'WA');
locations.mycity();
// I hope to TTH to make a refresh courses for old courses.
1 Answer
Steven Parker
231,236 PointsThe course example shows the creation of a function for constructing an object, and then using it with the "new" operator to make a new object instance. Then a method is called on the object. In that example, "this" represents the new object ("locations") that is constructed.
Your code is doing something different. By calling the function directly, no object is created but two global variables and a global function are created. And then you call the global function. In your code, "this" represents the global context instead of a new object.
Also, the MDN documentation for Arrow Functions says they "are best suited for non-method functions" and explains how they don't establish their own "this" like conventional functions do. If you used your function to create an object (using "new"), you could see this difference by calling the method from another context. The object method using the arrow function would completely ignore the new context:
locations.mycity.call({name: "Miami", state: "FL"});
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsBrendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsNot sure what course this is, but it was probably done before ES6.