'Prototype members

What is the difference if we define a method in the constructor function or we define it in the prototype of the constructer?

I know that if we define it in the constructer itself it would be a waste of memory but why it wouldn't be in the prototype?

In the constructor

function Circle(){
    this.draw() = function(){           
        console.log('draw')
    }
}

In the prototype

Circle.prototype.draw = function(){
    console.log('draw')
}



Solution 1:[1]

The constructor is typically used to define data that is specific to each object. So if you create 5 objects of a certain type then there would also be 5 different sets of data properties, one set per each object. If you start including function definitions in the constructor these functions would also be multiplied, one for each instance of the object. This would not be a good use of memory. In contrast, prototype is basically a JavaScript OOP feature that stores one copy of properties common to each instance of a certain type of object. So when you add a function to the prototype, there is only one copy of it and that one copy is used by every instance of the object. This makes sense since objects of the same type would have the same behavior - the same functions - so no need to waste memory with multiple copies of the same function when multiple objects can share the same one copy and just use different data in the arguments or different data pulled from the unique data stored in each object as defined by the constructor.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Caribbean Coder