将值作为函数参数传递给匿名函数

时间:2017-02-10 21:24:40

标签: javascript function scope

y1和year1在匿名函数中未定义,这是circle.attr()的参数。但是,在代码进入circle.attr()之前,'year1'确实具有正确的值。有人可以解释为什么会这样吗? **我确实通过将第二个参数替换为“xYear(y)”

来使函数工作
function circleLocation(y) {
  year1 = y
  console.log(year1)
  circle.attr('cx', function(year1) {
    y1 = year1;
    console.log(y1)
    console.log(year1)
    return xYear(y);
  })
}

3 个答案:

答案 0 :(得分:2)

您正在重新定义year1。函数的参数就像它们的范围内的变量。所以这个:

function (year1) {
    // ...

或多或少与:(具有相同的效果,但它不是一回事)

function() {
    var year1;
    // ...

year1变量正在影响另一个year1(你想要的那个)。试试这个:

circle.attr('cx', function() { // without the argument year1
    y1 = year1;
    console.log(y1)
    console.log(year1)
    return xYear(y);
})

答案 1 :(得分:1)

首先,看起来你正在引入全局变量,所以我建议使用var来防止这种情况发生。

var year1 = y;

接下来,我很难理解,但我认为你在执行匿名函数之前为什么year1有一个值以及为什么它在匿名函数中是undefined时感到困惑。

这里的问题是你阴影另一个变量。您的匿名函数采用名为year1

的参数
circle.attr('cx', function(year1) {
  ...

这意味着您已在该函数范围内声明了名为year1的变量。无论何时在范围内声明变量,该声明都会影响前一个声明。这意味着,它是一个全新的变量,与之前的变量无关。

var x = 2;

function useGlobal() {
  // No x is declared here so it grabs the next available x value
  // which is the global one
  console.log(x);
}

function hideX(x) {
  // Here we've said that the function takes a parameter named x
  // This means we can no longer access the outer variable named x
  console.log(x); // undefined
}

function declareX() {
  // Same thing as before, we've declared a new x so the old
  // one is shadowed
  var x = 500;
  console.log(x);
}

useGlobal();
hideX();
declareX();

// Notice how declareX didn't change the original x
useGlobal();

答案 2 :(得分:0)

你没有在函数circleLocation(args)中引入参数

function circleLocation(y) {
  year1 = y
  console.log(year1)
  attr('cx', function(year1) {
    y1 = year1;
    console.log(y1)
    console.log(year1)
    return xYear(y);
  })
}


function attr(n,fun){
}
circleLocation(4);

相关问题