user2952265 user2952265 - 7 months ago 71
Javascript Question

Why put functions outside objects?

I try to understand the concept of prototyping in JS. I found the following example. I asked myself, if the function is declared outside the object. Does it help to save ressources?


function Animal (name) { = name;
Animal.prototype.speak = function () {
console.log( + ' makes a noise.');


When you use a function as a Class in Javascript. Normally, string or number or other primitive properties are initialized inside the function; and methods go into the prototype (this does helps saving resources :) ). Just like your example code. There are other ways to achieve the same "classy behavior", but using prototype is the most basic way.