An alternative to solve your problem would be to use overload.
Ex: Overload - Number of parameters
Once again I will use Js "apply" method to solve this question, as the language moves a lot with prototypes and constructors, nothing more intelligent than using this scope method. The idea I had was to use a function as a function and at the same time as an object that holds its own properties.
var Person = {
Class: function(){
//Private
var name = ''
//Public
this.name = function(){
return this.name[ arguments.length ].apply( this, arguments )
}
this.name[0] = function(){ return name }
this.name[1] = function(n){ name = n }
this.name[2] = function(a, b){ name = a + " " + b }
}
}
Here I create a function ( method ) with name "name" and create 3 more properties of it that are: 0, 1 and 2. They are numbers, but still are properties of the name method. What the main function will do is see how many parameters it has and will call its corresponding property, which is nothing more than another method that will be executed in the same context as the name and will have the same parameters as the name.
Soon:
var Edu = new Person.Class
Edu .name() // ''
Edu .name('Eduardo')
Edu . name() // "Eduardo"
Edu . name('Eduardo', 'Ottaviani')
Edu . name() // "Eduardo Ottaviani"
It is not because I had this idea not, but I consider this the most elegant form of operator overload so far. Perhaps it is not the most efficient, I have not tested its speed in relation to other techniques. If it is slower, I believe it is not noticeable.
Source.: https://javiani.wordpress.com/2010/04/17/overload-em-javascript/