Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Object-Oriented JavaScript (2015) Constructor Functions and Prototypes Methods with Prototypes

Leigh Maher
Leigh Maher
21,830 Points

Running the roll function again and again

In this video Andrew moves the function out of the object because he says that it means the function, if left inside the object, has to run again and again.

I don't really get this. Doesn't this function have to run each time you pass a different number into i.e. the sides argument that gets passed in? This has to be passed into function, whether it lives inside our outside the object.

2 Answers

If you have an anonymous function in the object, a new copy of the function will be created with every instance of the object. If you move it outside the function and reference it, it will only be there once. So if you would have 100 instances of an object, you would also have 100 copys of the anonymous functions inside the object which would eventually clutter up the memory.

Leigh Maher
Leigh Maher
21,830 Points

Ah, ok. So, every instance of an object makes a copy of the code from that object? But we don't actually see that code, it's just contained within the instance that we create. And the function does run each time we create an instance of the object, but the function is just referenced?