我想不出一种方法可以解释我所追求的东西,而不是我在标题中所做的,所以我会重复一遍.从对象内调用的匿名函数是否可以访问该对象的范围?以下代码块应该解释我正在尝试做的比我更好:
function myObj(testFunc) {
this.testFunc = testFunc;
this.Foo = function Foo(test) {
this.test = test;
this.saySomething = function(text) {
alert(text);
};
};
var Foo = this.Foo;
this.testFunc.apply(this);
}
var test = new myObj(function() {
var test = new Foo();
test.saySomething("Hello world");
});
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我收到一个错误:"没有定义Foo." Foo
当我调用匿名函数时,如何确保定义?这是一个进一步实验的jsFiddle.
编辑:我知道将这行添加var Foo = this.Foo;
到我传入我的实例的匿名函数中myObj
会使这个工作.但是,我想避免在匿名函数中公开变量 - 我还有其他选择吗?
应该是this.Foo
:
var test = new myObj(function() {
var test = new this.Foo();
test.saySomething("Hello world");
});
Run Code Online (Sandbox Code Playgroud)
或者使用with
:
var test = new myObj(function() {
with (this) {
var test = new Foo();
test.saySomething("Hello world");
}
});
Run Code Online (Sandbox Code Playgroud)