简体   繁体   中英

Right way to create Libraries in Javascript

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.

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');
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM