I have an an object called SineMacula
which houses many methods for creating form elements and making these form elements do things on a page.
Firstly, when the page loads, a method called setFields()
is called which loops through all the fields on a page and sets them appropriately i.e. autocomplete, checkbox etc...
The code for setFields()
looks like this:
/**
* Set Fields
* This function will set all fields
*
* The options:
* - fields: the fields selector to loop through
*
* @param object options The field options
*/
SineMacula.prototype.setFields = function (options){
// Set the defaults for the fields
var options = $.extend({
fields: '.field', // Define the default field selector
},options);
// Loop through the fields and set the events
$(options.fields).each(function(){
// Set the field events
SineMacula.setBlur($(this));
SineMacula.setFocus($(this));
SineMacula.setToggleLabel($(this));
// If the field is a checkbox then set it
if($(this).parent().hasClass('checkbox')){
SineMacula.setCheckbox($(this).parent());
}
// If the field is an autocomplete then set it
if($(this).parent().hasClass('autocomplete')){
SineMacula.setDropdown($(this).parent(),{source:$(this).attr('data-source')});
}
// etc...
});
};
Most of the code above can be ignored, but I have inserted all of it so that you can see exactly what I am doing.
I have quite a few methods of the SineMacula
object such as setCheckbox()
, setDropdown()
...
What I would like to know is, should I be treating these methods as objects in themselves?
So should my code look like this instead:
if($(this).parent().hasClass('autocomplete')){
new SineMacula.dropdown($(this).parent(),{source:$(this).attr('data-source')});
}
Notice the new
keyword before calling the dropdown()
method.
Is this a better method of working things? Will be use less memory etc?
There is no reason to create an instance of an object only to call the constructor and then throw the object away. By doing the work in the constructor you are just using it as a regular function, but with the overhead of creating an unused object.
(In fact you don't seem to use the SineMacula instance for anything either, other than as a namespace for the methods.)