admin管理员组文章数量:1291174
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?
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?
Share Improve this question edited Jul 5, 2010 at 11:41 gblazex 50.1k12 gold badges99 silver badges92 bronze badges asked Jul 5, 2010 at 11:31 Alex IvasyuvAlex Ivasyuv 8,84417 gold badges75 silver badges91 bronze badges 02 Answers
Reset to default 9I still wonder why you would make functions to be private, that are needed outside... But there you go:
(function() {
var a = 1;
var b = 2;
var obj = {
f1: function() {
},
f2: function() {
}
}
externalFunction(obj);
})();
function externalFunction(pointer) {
pointer.f1(); // win
}
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:
externalFunction({ f1: f1, f2: f2 });
本文标签: oopjavascript anonymous function scopeStack Overflow
版权声明:本文标题:oop - javascript anonymous function scope - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741504391a2382232.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论