user2952265 user2952265 - 1 month ago 19
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?

JS

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

Answer

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.