将函数作为参数传递给JS并访问接收函数的变量

时间:2016-04-05 12:37:50

标签: javascript function scope

我不确定这在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'

2 个答案:

答案 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'

并告诉我们您是否需要。 感谢