我相信你已经经历了很多次,但我无法弄清楚一个真正符合我需要的线索。
我怎样才能让var inner在上面工作?
function outerOne(){
/* do something*/
var inner = function(){
return true
}; inner();
};
outerOne()
function outerTwo(){
if (inner==true)
/* do something*/
};
outerTwo();
请注意,我知道可以将var x声明为外部以使其全局化。 但我想要实现的是从函数内部获取var的范围
答案 0 :(得分: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();
答案 1 :(得分:1)
也许您可以将代码重组为类似
的代码var obj =
{
outerOne : function(){return true;//or whatever logic you need here
},
outerTwo : function(){
if(this.outerOne() === true){
//do something
}
}
}
obj.outerTwo();
答案 2 :(得分:1)
将您的代码包裹在IIFE中。并将inner设置为顶部的未定义变量。
(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();
})();
答案 3 :(得分: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();