2017-02-10 244 views
0

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); 
    }) 
} 

回答

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); 
}) 
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);

1

首先,它看起来像你介绍的全局变量,因此我们建议使用var防止这发生了。

var year1 = y; 

下,很难理解,但我认为你搞不清楚为什么year1具有执行您的匿名函数之前的值,它为什么undefined匿名函数内。

这里的问题在于你是shadowing另一个变量。您的匿名函数采用名为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();

相关问题