lundi 19 décembre 2016

Constructor vs object literal vs raveling module pattern

It has been awhile I write spagetti code using javascript. I tried to organize my code but I'm confused which one to use and when to use certain pattern.

constructor pattern

function foods(food){
  this.food = food;
  this.eat = function(){
    return 'I"m eating ' + this.food;
  }
}

var eatApple = new foods("apple");
console.log(eatApple.eat()); 

var eatBanana = new foods("banana");
console.log(eatBanana.eat()); 

object literal

var foods = {
  food : null,
  eat : function(){
    return 'I"m eating ' + this.food;
  }
};

foods.food = 'apple';
console.log(foods.eat());

foods.food = 'banana';
console.log(foods.eat());

revealing module

var foods = function(){
  var defaultFood = "default food";
  function eat(food){
    //this is ugly
    if(food){
      food = food;
    }else{
      food = defaultFood;
    }
    return 'I\"m eating ' + food;
  }

  return {
    eat: eat
  };
}();

var justEating = foods.eat();
var eatingApple = foods.eat('apple');
var eatingBanana = foods.eat('banana');

console.log(justEating);
console.log(eatingApple);
console.log(eatingBanana);

I think object literal is the most common use, why isn't everybody just use that? And is revealing module still relevant in 2016? most people will just do module.exports.

Aucun commentaire:

Enregistrer un commentaire