this Vs. prototype [duplicate]

Defining a function with whatever = function() { ... } tends to create what’s called a “closure”, where the function can access local variables of the function that defines it. When you say this.fn = function() { ... }, each object gets an instance of the function (and a new closure). This is often used to create “private” variables in Javascript, but comes with a cost: each function (in each object) is distinct, and takes up more memory.

When you say Rectangle.prototype.fn = function() { ... }, one instance of the function is shared by all Rectangles. This saves memory, and can minimize some memory leaks in browsers that handle closures badly. If you don’t need “private” members, or other such access to the defining function’s local variables, it’s usually a better idea.

Leave a Comment