JavaScript - 修改之前声明的var,在另一个函数返回的函数中?

时间:2017-05-08 08:43:03

标签: javascript variables

我正面临着JavaScript的变量引用问题..使其易于理解的最佳方法是显示我的代码:

var compiledCode = '';
var lastOutput;

/* ... */

callingFunc(
       function (lastOutput, compiledCode) {
         return function() {
           /* This trims back the lastOutput from compiledCode */
           var trimBackLength = lastOutput.split('\n').length;

           var tmpVar = compiledCode.split('\n');
           tmpVar.splice(0, -trimBackLength);
           compiledCode = tmpVar.join('\n');

           /* And then returns the lastOutput */
           return lastOutput;
         };
       }(lastOutput, compiledCode)
    );

我希望我的功能可以这样使用:

function callingFunc(newFunc) {
  var v = newFunc();
}

所以我的问题是当我调用“newFunc()”时,又称。匿名函数,它返回我想要的但它不会修剪全局变量...
你能告诉我在哪里发生错误吗? 谢谢提前!

1 个答案:

答案 0 :(得分:0)

  

它不会修剪全局变量

当然不是,因为它没有使用任何全局变量。 compiledCode变量是本地声明为IIFE参数的变量。

似乎没有理由在你的代码中使用它,只需放弃整个IIFE。

var compiledCode = '';
var lastOutput; // you forgot to initialise this

/* ... */

callingFunc(function() {
    /* This trims back the lastOutput from compiledCode */
    var trimBackLength = lastOutput.split('\n').length;
    var tmpVar = compiledCode.split('\n');
    tmpVar.splice(0, -trimBackLength);
    compiledCode = tmpVar.join('\n');

    /* And then returns the lastOutput */
    return lastOutput;
});