Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why defining properties in the prototype is considered an antipattern

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

like image 223
opensas Avatar asked Aug 10 '12 14:08

opensas


2 Answers

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 write

function Person(name) {
    this.name = name;
}

i.e. the property name must be set in the constructor.

Of course, you can write

function Person(name) {
    this.name = name;
    this.describe = function() { ... };
}

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:

Person.prototype.describe = function () {
    return "Person called "+this.name;
};

you only define the method once. All instances of Person will receive a pointer (called __proto__ and not accessible by programmer in most browsers) to Person.prototype. So if you call

var myPerson = new Person();
myPerson.describe();

it 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.

like image 55
Imp Avatar answered Sep 20 '22 14:09

Imp


There's nothing wrong with that code. This is supposedly what is meant:

function Person(name) {
    this.name = name;
}
Person.prototype.age = 15; //<= adding a hardcoded property to the prototype

Now you will see this:

var pete = new Person('Pete'), mary = new Person('Mary');
pete.age; //=> 15
mary.age  //=> 15

And most of the time, that's not what you want. Properties assigned to the prototype of a constructor are shared between all instances, properties assigned within the constructor (this.name) are specific for the instance.

like image 21
KooiInc Avatar answered Sep 21 '22 14:09

KooiInc