Reputation: 1829
y1 and year1 are undefined inside the anonymous function, which is a parameter to circle.attr(). However, 'year1' does have the right value before the code enters circle.attr(). Could someone explain why this is? **I did get the function to work by replacing the 2nd parameter with "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);
})
}
Upvotes: 0
Views: 52
Reputation: 31692
You are redefining year1
. Arguments of a function are like variables inside their scope. So this:
function (year1) {
// ...
Is more or less the same as: (has the same effect but it's not the same thing)
function() {
var year1;
// ...
The year1
variable is shadowing the other year1
(the one you want). Try this:
circle.attr('cx', function() { // without the argument year1
y1 = year1;
console.log(y1)
console.log(year1)
return xYear(y);
})
Upvotes: 2
Reputation: 32511
First off, it looks like you're introducing global variables so I'd suggest using var
to prevent this from happening.
var year1 = y;
Next, it's hard to understand but I think you're confused about why year1
has a value before executing your anonymous function and why it's undefined
inside of the anonymous function.
The problem here is that you're shadowing the other variable. Your anonymous function takes a parameter named year1
circle.attr('cx', function(year1) {
...
That means you have declared a variable named year1
inside of that functions scope. Whenever you declare a variable inside of a scope, that declaration will shadow the previous declaration. That means, it's a whole new variable and doesn't correlate with the previous one.
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();
Upvotes: 1
Reputation:
you not have introduced a parameters in function 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);
Upvotes: 0