带有闭包的Javascript构造函数,使用外部变量引用其他变量

时间:2014-10-03 15:19:06

标签: javascript closures

var Beer = function(){
    var moreBot = 100,
        lessBot = 10,
        wholeCase =  moreBot + lessBot;

    this.count = function(){
        moreBot = 22; 
        lessBot = 33;
        console.log(moreBot); //returns 22
        console.log(lessBot); //returns 33
        return wholeCase; //returns 110 instead of 55??
    };
};

var Alc = new Beer();

所以说我有这个构造函数使用一个引用外部函数变量的闭包。那么为什么当我在更改变量moreBot和lessBot之后返回wholeCase时,我得到最初赋值的总和?提前感谢您的专业知识!

1 个答案:

答案 0 :(得分:0)

wholeCase在施工时设置。您的示例与以下内容没有显着差异:

var foo = 5,
    bar = 6;
var sum = foo + bar; // sum is 11

foo = 100000;
console.log(sum); // sum is still 11; we never changed sum

每次使用时都需要重新计算wholeCase,或者只是让它成为一个函数:

var Beer = function(){
    var moreBot = 100,
        lessBot = 10,
        computeWholeCase = function() { return moreBot + lessBot };

    this.count = function(){
        moreBot = 22; 
        lessBot = 33;

        return computeWholeCase(); // run computeWholeCase to return 55
    };
};