I know there are similar questions like this one, but I want to see if these answers remain valid when optimized in the new Javascript engines.
In my opinion, the greatest advantage in defining functions inside the constructor is that you can easily avoid having to know the meaning of the 'this' keyword:
var Person = function() { var self = this; self.firstName = null; self.lastName = null; self.fullName = function() { return self.firstName + self.lastName; }; };
This approach is recommended by Knockout Management 'this' . This is a big advantage, especially when the code is modified by many developers, because it is very easy to understand and use.
Another approach would be to use a prototype object:
var Person = function() { this.firstName = null; this.lastName = null; }; Person.prototype.fullName = function() { return this.firstName + this.lastName; };
In this case, there are performance advantages, since object objects will be created once. However, the main problem I am facing is that it would be difficult to process the 'this' keyword. The above example is very simple, but if you have event handlers for all calls, jQuery calls each (), methods called from different contexts, etc., this is easy to mess up.
Of course, if you understand how 'this' works and know how the method is called, you should not have many problems. However, in my experience, this takes time, and it is error prone, especially when the code is created by many developers.
I know that new JS engines, such as V8, apply optimizations to cases where you declare functions inside the constructor, creating hidden classes: How does the V8 engine work? .
So my question is that, given these optimizations made by the new JS machines and the complexity of processing the 'this' keyword, does it make sense to use a prototype approach? What would I lose using the approach of putting everything inside the constructor?
UPDATE 1:
I just made a micro benchmark in Chrome (version 42). I create 1M objects with functions inside the constructor and functions in the prototype. This is a very simple object with two variables and three functions, and the results look like this:
Functions inside constructor: 1.91 seconds Functions in prototype: 1.10 seconds
It seems that even with those optimizations in the V8, it is still 73% faster. However, it was a micro benchmark. Not sure if this will be a big difference in real applications.
UPDATE 2:
I also looked at memory consumption, and there are big differences. For functions inside constructors:
Shallow size: 64,000,120 Retained size: 336,001,128
For prototype functions:
Shallow size: 40,000,000 Retained size: 40,000,000
Either optimization with a hidden class is not so good, or I missed something. I use monomorphic code (constructors without arguments) as suggested by V8, but not sure if I am doing something wrong.
UPDATE 3:
Here is the link of the test I did if someone can point out something is wrong: http://jsperf.com/dg-constructor-vs-prototype