I completely understand why it's better to use the prototype instead of the constructor to define a class method, (i.e. Use of 'prototype' vs. 'this' in JavaScript?) However, I recently came across a HashMap class that defines the count
property in the prototype and the map
property in the constructor:
js_cols.HashMap = function(opt_map, var_args) {
/**
* Underlying JS object used to implement the map.
* @type {!Object}
* @private
*/
this.map_ = {};
/...
}
/**
* The number of key value pairs in the map.
* @private
* @type {number}
*/
js_cols.HashMap.prototype.count_ = 0;
Are there advantages of declaring an instance property like count
in the prototype instead of saying this.count_ = 0;
in the constructor? And if so, why not also js_cols.HashMap.prototype.map_ = {};
?
Edit: A similar question was asked, Why declare properties on the prototype for instance variables in JavaScript, and "default values" was raised as a use case, but it was not explained why this is more desirable than just defining the default value in the constructor.