2011-09-11 85 views

回答

3

您可以用电话或APPY改变范围:

function jCamp(code){ 
    function test(){ 
     alert(); 
    } 
    code.call(test); 
} 
jCamp(function(){ 
    this(); 
}); 

所以我们改变this引用私有函数

+0

这样做。谢谢! –

1

试验(+)是匿名函数,参数JCAMP()没有定义(这是第8行的一个,如果你不改变你的代码)中调用。功能test()仅在jCamp()的定义内部定义。

+0

那么无论如何,它使一个函数只能通过jCamp()的参数函数调用? –

0
function jCamp(code){ 
    this.test = function(){ 
     alert("test"); 
    } 
    code(); 
} 
jCamp(function(){ 
    this.test(); 
}); 

我会做这种方式。

0

test是一个私人功能,只能在jCamp内使用。您不能从作为参数传递的匿名函数中调用它。你可以把它的属性,虽然,这样的:

function jCamp(code){ 
    this.test = function(){ 
     alert(); 
    } 
    code(); 
} 
jCamp(function(){ 
    this.test(); 
}); 
+0

请注意,这将实际存储全局'test',因为'this'是'window'。 – delnan

0

功能的范围时,它是创建,而不是当它被称为是确定的。

var a = 1; // This is the a that will be alerted 
function foo(arg) { 
     var a = 2; 
     arg(); 
} 
foo(function() { alert(a); }); 
相关问题