我不确定这在Javascript中是否可行。我想通过传递的函数访问函数的变量,(或者如果函数是通过' onend'调用传递的话)。
function Outer() {
var fn;
var foo = 'this is foo';
this.bar = function(x) {
fn();
}
this.setFunction = function(f) {
fn = f;
}
}
var o = new Outer();
o.setFunction(function() {
alert(foo); //doesn't work
});
o.bar(); //want to alert 'this is foo'
答案 0 :(得分:2)
fn
在功能上是一个回调。使用本地foo
变量作为参数调用回调函数:
function Outer() {
var fn;
var foo = 'this is foo';
this.bar = function() {
fn(foo);
}
this.setFunction = function(f) {
fn = f;
}
}
var o = new Outer();
o.setFunction(function(foo) {
alert(foo);
});
o.bar();
答案 1 :(得分:1)
你能试试吗
function Outer() {
var fn;
this.foo = 'this is foo';
this.bar = function(x) {
fn();
}
this.setFunction = function(f) {
fn = f;
}
}
var o = new Outer();
o.setFunction(function() {
alert(o.foo);
});
o.bar(); //want to alert 'this is foo'
并告诉我们您是否需要。 感谢