0

Im trying to understand the good way of building objects. I expose two ways. Which is the best way to define an object. If both of them are fine what are the pros and cons of each one?

    var your_drink="tekila";// yes, i love tekila :)
//your_drink="";
var reverse=function(s)
{
    return s.split("").reverse().join("");
};
/*
Building objects in js.
*/ 
//first
var bartender = {
    str1: "ers",
    str2: reverse("rap"),
    str3: "amet",
    request: function(preference)
    {
        return preference+".secret word:"+this.str2+this.str3+this.str1;
    }
};
//alert result: tekila.secret word:parameters
alert(bartender.request(your_drink));
//second
var bartender = function()
{
    var str1="ers";
    var str2=reverse("rap");
    var str3="amet";
    this.request = function(preference)
    {
        return preference+".secret word:"+str2+str3+str1;
    }
};
var oBartender = new bartender();
//alert result: tekila.secret word:parameters
alert(oBartender.request(your_drink));
ioedu
  • 27
  • 8
  • Also, http://stackoverflow.com/questions/4859800/should-i-be-using-object-literals-or-constructor-functions and http://stackoverflow.com/questions/12356994/literal-notation-vs-constructor-to-create-objects-in-javascript. These are even more on-topic. – Yeldar Kurmangaliyev Nov 18 '15 at 09:44
  • @Azzi Please, can you explain why? – ioedu Nov 18 '15 at 09:54
  • The second way gives you encapsulation for private attributes. You would access the private attributes using getters and setters, the way that most of POO languages do. – ioedu Nov 18 '15 at 09:58

1 Answers1

0

Food for thought

But the second way is the way to go. And read to learn about prototyping to be able to instaciate your class

To be honest I have been doing JS for some time, did not take time to read about Classes and inheritance. Now that I have, I can tell you that time will not be wasted

Tons of resources out there, some are way more accessible than others

kartsims
  • 1,001
  • 9
  • 16