Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better Javascript object pattern [closed]

Which is a better Javascript object pattern ...

function dog(name) {
  this.name = name;
  this.getName = function() {
    return this.name;
  };
};

OR

function cat(name) {
  this.name = name;
};
cat.prototype.getName = function() {
  return this.name;
};

AND WHY?

----- edits

Does one or the other use more memory?

Is one more or less "CPU" intensive than the other?

Which is more maintainable?

Which is more scalable?

Which is more readable?

like image 728
Mark Peterson Avatar asked Aug 22 '11 04:08

Mark Peterson


1 Answers

Preferences aside, the second example is the "right" one. In the first one, you're creating a new getName function for every object. In 2, all objects created with this constructor will share the prototype/getName. Change it in one place and it will change for every instance.

On special occasions (like complex inheritance chains) you might need to use the first, but be aware of it's drawbacks.

This blog post might help you understand prototypal inheritance better.

like image 72
Ricardo Tomasi Avatar answered Sep 19 '22 10:09

Ricardo Tomasi