在Javascript中创建库的正确方法

时间:2016-04-26 15:37:37

标签: javascript javascript-objects

任何人都可以告诉我从以下选项创建库的正确方法。

     //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(); 
        }
     }

我想知道哪个是在其中创建对象和函数的正确方法。如果所有三个选项都错了,任何人都可以告诉我正确的方法。

1 个答案:

答案 0 :(得分:1)

然而,我个人的偏好,有很多方法可以给猫皮肤。随意更改变量等名称...

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