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
Devjyoti Ghosh
2,422 PointsWhy is showData not a function?
In the following code what exactly is showData why is it not a function?
// This data variable is a global variable
var data = [
{name:"Samantha", age:12},
{name:"Alexis", age:14}
];
var user = {
// this data variable is a property on the user object
data :[
{name:"T. Woods", age:37},
{name:"P. Mickelson", age:43}
],
showData:function (event) {
var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1
// This line is adding a random person from the data array to the text field
console.log (this.data[randomNum].name + " " + this.data[randomNum].age);
}
}
// Assign the user.showData to a variable
var showUserData = user.showData;
// When we execute the showUserData function, the values printed to the console are from the global data array, not from the data array in the user object
//
showUserData (); // Samantha 12 (from the global data array)
It acts like a method of user object but when assigning it to showUserData it is not using user.showData()
1 Answer
andren
28,558 PointsIs just a normal function stored in a property on the user object. You could call it directly like this user.showData() without any issues.
The thing is that in JavaScript functions are considered a type of value, just like strings, numbers, objects, etc. So you can copy them and pass them around in the exact same way you would any other value. That's why functions can be assigned to variables and properties.
So in this line:
var showUserData = user.showData;
You are just taking the function stored in user.showData and assigning it to the showUserData variable. As far as JavaScript is concerned this is no more special than copying a string or number from one variable to another.
The thing is though that the function makes reference to this, when the function is called from the object this would be referring to the object itself. But when you make a copy of the function and place it in a global variable this no longer refers to the object, but to the global namespace. Which is why this.data ends up pointing to the data object in the global namespace rather than the one found within the user object.
Devjyoti Ghosh
2,422 PointsDevjyoti Ghosh
2,422 PointsAny way I can create a new variable and have it point to the user object?