我真的希望这不是重复的。
function a(){ b(); } // function a calls function b; but there's no function b in the global scope...
(function(){
// the purpose was to declare it later because it may collide with user-defined functions
var b = function(){ console.log('I am function b()'); };
a(); // doesn't work, obviously
a.call(this); // also doesn't work
a.apply(this, []); // doesn't work either
// neither works
var scope = { 'b': function(){ return b.apply(this,arguments); } };
with(scope){
a.call(scope);
}
// ... what works then?
}());
简单来说,全局声明的函数a()
调用函数b()
。函数 b()
未在 a()
之前声明,并且不会属于同一作用域。
所以:
- 我们不能修改函数
a()
,也不能修改它的定义位置 - 我们不能在与
a()
相同的范围内声明b()
- 我们也不能
var a = eval(a().toString())
或任何类似的作弊
使用纯范围处理,这可能吗?如果不是,我们还能做什么? 只是想在这里学习一些 JavaScript 就够了。
最佳答案
你做不到。范围内的局部变量不能在该范围外访问,这就是范围界定的全部意义。如果想让b()
函数在匿名函数外可见,需要将其赋值给外部变量。
关于javascript - 将范围变量传递给在该范围之外声明的闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24240537/