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

in this instance, what is "this" referring to?

//listItem is declared inside this function.  To this point in my learning
//it usually seems to be that "this" would be the object that is clicked on
//that's not happening here
// the object up the chain is the function itself
//so the parent node of the function?
//I'm so confused
//Do objects have parents?


var taskIncomplete = function() {
 //what is "this" referring to?
  var listItem = this.parentNode;
  incompleteTasksHolder.appendChild(listItem);
  bindTaskEvents(listItem, taskCompleted);
}

Tack sรฅ mycket , รคr du alltid insikts

1 Answer

Martin Cornejo Saavedra
Martin Cornejo Saavedra
18,132 Points

It depends on the context. That function may be bind to a click event, then 'this' would be the clicked element.

For example, a checkbox:

var checkbox = document.getElementById("my_checkbox");
checkbox.onchange = taskIncomplete;

Yes, that's what's happening here. Now that makes perfect sense. Thank you.

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi John! Glad you got your question answered. Thought I'd throw in my two cents also. Had that not been attached to an event then the this would have referred to the global object (the window/document) which would have a parent node of undefined. Take a look at this small snippet in the console:

function func1(){
  return this;
}

console.log(func1());

Just a bit of trivia for you :sparkles:

Martin Cornejo Saavedra
Martin Cornejo Saavedra
18,132 Points

Jennifer, that's interesting thanks for sharing.