0

Could any one tell me the right way to create libraries from below options.

     //option 1

     function Fruit(){
       var color,shape;
       this.start = function(l,callback){
         color = "Red"; shape = "Circle";
         return callback();
       }           
     }

    //option2

    function Fruit(){

       this.start = function(l,callback){
         this.color = "Red"; this.shape = "Circle";
         return callback();
       }           
     }

     //option3

    var Fruit = {
        var color,shape;
        start : function (l,callback) {
             color = "Red"; shape = "Circle";
             return callback(); 
        }
     }

I want to know which is the right way to create Objects and Functions inside of it. If all three options are wrong, could any one tell me the right way.

  • Your option 3 is a syntax error, so it's not an option. Also it seems to create an object, not a constructor function. – Bergi Apr 26 '16 at 15:40
  • You might want to have a look at [Javascript: Do I need to put this.var for every variable in an object?](http://stackoverflow.com/q/13418669/1048572) for the difference between your first two options. However, there are many ways to write libraries with class constructors, all of them different, and none of them wrong - there is no "right way". – Bergi Apr 26 '16 at 15:44
  • I flagged the question because they are as many "good" ways to create objects than expert javascript developers and libraries – Regis Portalez Apr 26 '16 at 15:54

1 Answers1

1

My personal preference, however, there are many ways of skinning a cat. Feel free to change the names of vars etc...

//option 4

 function Fruit(_fruit, _callback){
   var that = this;
   this.color = '';
   this.shape = '';

   var init = function(f, c){
     switch(f){
       case 'apple':
         that.color = 'red';
         that.shape = 'circle'
       break;
     }
     return c();
   }

   init(_fruit, _callback);           
 }

 var apple = new Fruit('apple', function(){
   // Although you don't really need a callback as you're not doing any async tasks...
   alert('Apple generated');
 });
Flux
  • 391
  • 2
  • 14