JavaScript 匿名函数作用域
我有以下匿名函数:
(function() {
var a = 1;
var b = 2;
function f1() {
}
function f2() {
}
// this => window object!
// externalFunction(this);
})();
function externalFunction(pointer) {
// pointer.f1(); => fail!
}
我需要从此匿名函数调用外部函数并将其指针传递给调用函数 f1 & f2。 但我不能这样做,因为 this 引用的是窗口对象而不是内部范围。
我可以将函数设置为:
this.f1 = function() {}
但这是个坏主意,因为它们将位于全局空间中...
我如何将匿名空间传递给外部函数?
I have the following anonymous function:
(function() {
var a = 1;
var b = 2;
function f1() {
}
function f2() {
}
// this => window object!
// externalFunction(this);
})();
function externalFunction(pointer) {
// pointer.f1(); => fail!
}
I need to call external function from this anonymous function and pass it's pointer to call functions f1 & f2.
But I can't do this, as this refer to window object instead of internal scope.
I can set function as:
this.f1 = function() {}
but it's bad idea, as they'll be in global space...
How I can pass anonymous space to external function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我仍然想知道为什么你要把外部需要的函数设为私有......
但是就这样:
或者您可以单独传递 f1 和 f2,那么您不需要将它们放入对象中。
I still wonder why you would make functions to be private, that are needed outside...
But there you go:
Or you can pass f1 and f2 individually, then you don't need to put them into an object.
您不能将作用域作为对象传递,但您可以使用作用域中所需的任何内容创建一个对象:
You can't pass the scope as an object, but you can create an object with whatever you want from the scope: