创建一个类来保存javascript中的全局变量

时间:2016-01-03 15:24:05

标签: javascript oop

我正在用javascript开发一个面向对象的程序。一切正常,但问题是我的代码中有太多的全局变量。

代码:

var Item = function(name, price){
    this.name = name;
    this.price = price;
    this.sells = 0;
}


var sphagety = new Item ("sphagety", 130);
var pizza = new Item("pizza", 150);
var macaroni = new Item("macaroni", 100);
var milk = new Item("milk", 20);
var cheese = new Item("cheese", 15);

// too many global variable
var total = 0;
var change = 0;
var result = 0;
var sellRecord = []; 
var sumOfSell = [];

var cash = {
    "sum" : [],
    "display" : function(disp){

        if (disp === total) {
             console.log("Total : Rp" + total);

        }
         else if(disp === result){
            console.log("subTotal : Rp" + result);
        }
        else if(disp === change){
            console.log("change : Rp" + change + "\nmuch obliged");
        };

        },

     "sell" : function(req, qty){
        for(var property in req)
        sells = req;
        sells.sells += qty;
        result = req.price * qty;
        total += result; 
        cash.save();
        cash.display(total);
        cash.display(result);


    },
    "void" : function(){
          var lastSell = sumOfSell.length;
          var lastRec = sellRecord.length;
          total -= sumOfSell[lastSell-1];
          delete sellRecord[lastRec-1];
          delete sumOfSell[lastSell-1];
    },
    "save" : function(){
        cash.total += result;
        sumOfSell.push(result);
        sellRecord.push({sells});
     },
     "change" : function(money){


     if(money > total){
        change -= (money - total);
        cash.display(change);
    }
    else if(money == total){
         console.log("much obliged");
         }

    if(money < result){
         alert("the money is didn't enough!!\n  " + (money - result) + "");
        }   
     }
 }
 //  transaction no 1
 cash.sell(pizza,3);
 cash.sell(pizza,3);
 cash.sell(milk,3);
 cash.sell(cheese,3);

然后我试图摆脱全局变量,我有一个想法,通过创建一个名为Session类的新类对象并将方法endSession添加到cash Object,但我最终坚持找出如何处理类之间的闭包。 我像这样修改了代码

// new Class (Session class) put the global variable inside
function Session (total, change, result, sellRecord, sumOfSell){
this.total = total;
this.change = change;
this.result = result;
this.sellRecord = sellRecord;
this.sumOfSell = sumOfSell;
}
 var cash = {
    "sum" : [],

    "display" : function(disp){

        if (disp === total) {
             console.log("Total : Rp" + total);

        }
         else if(disp === result){
            console.log("subTotal : Rp" + result);
        }
        else if(disp === change){
            console.log("change : Rp" + change + "\nmuch obliged");
        };

        },

     "sell" : function(req, qty){
        for(var property in req)
        sells = req;
        sells.sells += qty;
        Session.result = req.price * qty;
        Session.total += result; 
        cash.save();
        cash.display(total);
        cash.display(result);
    },
    // adding new cash method 
    "startSession" : function(){
        function session(){
            var session = {};
            var i = 1;
            session[i] = new Session(0,0,0,[],[]);
            //add
        }
     },
    "void" : function(){
          var lastSell = sumOfSell.length;
          var lastRec = sellRecord.length;
          total -= sumOfSell[lastSell-1];
          delete sellRecord[lastRec-1];
          delete sumOfSell[lastSell-1];
    },
    "save" : function(){
        cash.total += result;
        Session.sumOfSell.push(result);
        Session.sellRecord.push({sells});
     },
     "change" : function(money){


     if(money > total){
        change -= (money - total);
        cash.display(change);
    }
    else if(money == total){
         console.log("much obliged");
         }

    if(money < result){
         alert("the money is didn't enough!!\n  " + (money - result) + "");
        }   
     }
 }

我想知道我的想法是否可行?

2 个答案:

答案 0 :(得分:1)

你可以有这样的东西

function Session(){
    // These are private and can only be accessed via public methods
    var total = 0;
    // ....
    // Other local variables

    this.addProduct = function(item){
        total += item.price;
    }

    this.getTotal = function(){
        return total;
    }


}

然后你可以做类似

的事情
var cart = new Session();
cart.add(new Item ("sphagety", 130));
cart.add(new Item("milk", 20));
console.log(cart.getTotal()); // 150

请务必始终在SessionItem前面使用新关键字,否则您将产生不良后果。

答案 1 :(得分:0)

您可以使用sessionStorage。

  

sessionStorage只存储一个会话数据:)但是如果存储的话   每次您可以使用localStorage时的日期。

这是一个简单的sessionStorage示例; using sessionStorage with browser support control