Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Creating JS object ?

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #46257
    Kuzyo
    Participant

    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;

    }

    #142027
    Subash
    Member

    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.

    #142034
    Kuzyo
    Participant

    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”);**

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.