2017-02-10 10 views
0

y1とyear1は、匿名関数内では未定義です。これはcircle.attr()のパラメータです。しかし、 'year1'はコードが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

と第二パラメータを置き換えることで動作するように機能を手に入れました。関数の引数はスコープ内の変数と似ています。だから、この:(同じ効果を持っていますが、それは同じことではありません)

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

year1変数は、あなたがしたい他のyear1(1シャドウイングされていますよう

function (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だ理由について混乱だと思います。

ここでの問題は、シャドウイング他の変数です。あなたの無名関数を使用すると、その内側にyear1という名前の変数を宣言したことを意味しyear1

circle.attr('cx', function(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();