user2952265 user2952265 - 1 year ago 105
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.');

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download