The first method (let's call it type 1) adds the area()
function to the object itself. Every time you construct a circle
object with new
, its body will be copied (!) to the new instance.
The second method (type 2) adds the area()
function to the object prototype (the prototype is "one level up" in the hierarchy). Every time you create a new instance of circle
only the radius
property will be copied.
Now when you call area()
on an instance of the second object, JavaScript cannot find that function on the object itself. Now it "goes up" the prototype chain and uses the first function of that name it finds.
Now this has several implications:
- New objects instances will be smaller (less physical code)
- You can change the implementation of
area
for all existing objects of type 2 at once and while they live (by changing the prototype), you can't do that for type 1
- You can override the functionality of
area
in a single instance of type 2 while keeping the "original implementation" of the function around