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

creating a class to hold global variables in javascript

本文关键字:javascript 保存 全局变量 一个 创建      更新时间:2023-09-26

我正在用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对象中,但我最终陷入了如何处理类之间的闭包的困境。我修改了这个的代码

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

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

你可以有这样的

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前面使用新关键字,否则会产生不理想的结果。

您可以为此使用sessionStorage。

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

这是一个简单的sessionStorage示例;使用sessionStorage和浏览器支持控制