【问题标题】:Javascript constructor with closure using outside variables referencing other variables带有闭包的Javascript构造函数使用引用其他变量的外部变量
【发布时间】:2014-10-03 15:19:06
【问题描述】:
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 时,我得到了最初分配的值的总和?提前感谢您的专业知识!

【问题讨论】:

  • 你第二次忘了wholeCase = moreBot + lessBot。你必须告诉 JavaScript 为你做这件事。它不会自己解决。
  • 改变一个变量的值,从不神奇地改变另一个变量的值。在这方面,JavaScript 的行为与大多数其他语言一样。

标签: javascript closures


【解决方案1】:

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
    };
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    相关资源
    最近更新 更多