I often see this pattern to define javascript objects
function Person(name) {
this.name = name;
}
Person.prototype.describe = function () {
return "Person called "+this.name;
};
And in this article it says that adding properties directly to the prototype objct is considered an anti-pattern.
Coming from “classical class based” languages, having to define the properties apart from methods doesn’t sound quite right, moreoever in javascript, where a method should be just a property with a function value (am I right here?)
I wanted to know if anybody can explain this, or even suggest a better way to handle these situations
In usual object-oriented languages, you have a definition of the class describing members, methods and the constructor.
In JS, the definition of the “class” (it is not really class like in other languages… sometimes the term pseudoclass is used) is the constructor itself. If your object is parametrised by
name, it makes sense to writei.e. the property
namemust be set in the constructor.Of course, you can write
and it will work as you expect.
However, in this case you are creating a separate instance of the method with every call of the constructor.
On the other hand, here:
you only define the method once. All instances of
Personwill receive a pointer (called__proto__and not accessible by programmer in most browsers) toPerson.prototype. So if you callit will work, because JS looks object members directly in the object, then in its prototype etc. all the way up to
Object.prototype.The point is that in the second case, only one instance of the function will exist. Which you will probably agree that is a better design. And even if you don’t, it simply takes less memory.