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



我正面临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(("时,也就是。匿名函数,它返回了我想要的东西,但它不会在全局变量中修剪...
你能告诉我我在哪里做了一个mistke吗?
谢谢!

它不会在全局变量中修剪

当然不是,因为它不使用任何全局变量。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;
});

最新更新