- This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
Viewing 3 posts - 1 through 3 (of 3 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Creating JS object ?
Hi everyone.
I’m new to JS and programming, and have question about creating JS object. For example I need to create object with set of properties. Here two variants which is better or they both wrong. Thanks for help.
first:
//field odject
var $field = $(“#field”);
var field = {
width: $field.width(),
offsetTop: $field.offset().top,
offsetLeft: $field.offset().left,
offsetRight: $field.offset().left + $field.width(),
offsetBottom: $field.offset().top + $field.height()
};
second:
function field($sel){
//field odject
var $field = $($sel);
var offset = $field.offset();
var field = {
width: $field.width(),
offsetTop:offset.top,
offsetLeft: offset.left,
offsetRight: offset.left + $field.width(),
offsetBottom: offset.top + $field.height()
};
return field;
}
It depends on what you are trying to achieve. I prefer the first method for plain objects and second if i need to do some calculations before exposing the object.
As for me the second is more understandable. I can simple receive properties by **field.offsetTop** without needing call a function **var field = new field(“#field”);**