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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With