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

Can a "this" value cross "function borders"?

// deletesTask
function deleteTask (){this.parentNode.parentNode.removeChild(this.parentNode)}


// deletesTask if text input value is empty
function removeWhenEmpty (){ if(this.value==="") this.parentNode.parentNode.removeChild(this.parentNode)}

The code above currently works for my application. But originally I had tried to replace the code after the if statement in removeWhenEmpty with "deleteTask()", the function above, because it is the exact same thing. But it doesn't work. Instead I get the error "can't get parentNode of undefined" when the function is triggered. On closer inspection, I saw that the "this" being passed to the function was not the object that removeWhenEmpty was attached to, but the window object. Does this mean that value for "this" can't cross "function borders"? Sorry, I`m tired.

2 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi Ryan Scharfer

The this value is bound to the object that calls the function. If you call a function in the global scope -- that is, outside any other functions or objects -- this will be the window object. You can use the call() method to run a function and specifically assign an object to this:

deleteTask.call(DOMElement);

Now, even though you're calling the deleteTask() function in the context of the window, this will be the DOM ELement you pass to call()

I know this can be really confusing. Check out our video on Call and Apply: http://teamtreehouse.com/library/javascript-foundations/objects/call-and-apply

Awesome. Thanks Dave! I enjoy your videos.