2

我敢肯定你已经经历过很多次了,但我想不出一个真正适合我需要的线女巫。

如何让 var inner 在outertwo 中工作?

function outerOne(){

/* do something*/

    var inner = function(){
            return true 
    }; inner();

};
outerOne()


function outerTwo(){
    if (inner==true)
/* do something*/
};
outerTwo();

请注意,我知道可以在外部声明 var x 以使其全局化。但我想要实现的是从函数内部将 var 移出范围

4

4 回答 4

2

你有没有尝试过:

var x;
function outerOne(){

    /* do something*/

    var inner = function(){
        x = 5
        console.log(x + "  Works in inner()");       
    }; 
    inner();

    console.log(x + "  Works in outerOne()");
};
outerOne();

function outerTwo(){
    console.log(x + "  Works in outerTwo()");
};
outerTwo();

函数只与在其父作用域中声明的变量共享作用域。

编辑

为了完整起见,我可能会补充一点,没有什么能阻止您从函数中返回值:

function outerOne(){

    /* do something*/

    var inner = function(){
        var x = 5
        console.log(x + "  Works in inner()");
        return x;       
    }; 
    var x1 = inner();

    console.log(x1 + "  Works in outerOne()");
    return x1;
};
var x2 = outerOne();

function outerTwo(){
    console.log(x2 + "  Works in outerTwo()");
};
outerTwo();
于 2013-03-21T05:49:04.577 回答
1

也许您可以将代码重组为这样的

var obj = 
    {
        outerOne : function(){return true;//or whatever logic you need here
                          },

        outerTwo : function(){  
           if(this.outerOne() === true){
               //do something
           }
        }
    }

    obj.outerTwo();
于 2013-03-21T05:47:45.063 回答
1

将您的代码包装在IIFE中。并将内部设置为顶部的未定义变量。

(function(){
var inner;

  function outerOne(){
  /* do something*/

      inner = function(){
         return true 
      }; inner();
  };
  outerOne()

  function outerTwo(){
      if (inner==true){
        //inner has been set to true, do something
      }
      else{
        //Inner has not been set to true, do something else
      }
  };
  outerTwo();

})();
于 2013-03-21T05:58:23.390 回答
0

使变量“x”成为全局外部函数。

var x = 0; 
function outerOne(){   
 //code block

var inner = function(){
        x = 5
       console.log(x + "  Works in inner()");       
}; inner();
console.log(x + "  Works in outerOne()");
};
outerOne()


function outerTwo(){
console.log(x + "  Works in outerTwo()");
};
outerTwo();
于 2013-03-21T05:50:26.300 回答