クラスを使用したゴミの分別処理

by iwbjp

JavaScript

// ゴミ箱
var moeruBox = [];
var funenBox = [];

// ゴミクラス
var Rubbish = function(name, type){
  this.name = name;
  this.type = type;
};

// 処理の繰り返し
function repeat(arr, fn){
  for(var i=0, len=arr.length; i<len; i++){
    fn.call(arr[i]);
  }
}

// メイン処理
repeat(
  [
    new Rubbish('チラシ', 'moeru'),
    new Rubbish('空き缶', 'funen'),
    new Rubbish('紙くず', 'moeru')
  ],
  function(){
    if(this.type === 'moeru'){
      moeruBox.push(this);
    }
    else{
      moeruBox.push(this);
    }
  }
);


$.each(moeruBox, function(i, item){
  $("body").append(item.type + ': ' + item.name + '<br>');
});

$.each(funenBox, function(i, item){
  $("body").append(item.type + ': ' + item.name + '<br>');
});