I'm trying to assign a variable to itself in a function, and if the variable has the same name as an argument to the function it doesn't seem to work, but does if they're not the same name. A code example shows this more clearly.
Is this behavior I should expect? This is a pared down example for my d3 use case which prompted this question. I've shown that below as well.
Non working example
var a;
function assign(a) {
a = a;
}
assign("test")
console.log(a)
undefined
Working Example
var a;
function assign(b) {
a = b;
}
assign("test")
console.log(a)
test
Use case
var data
d3.csv("data.csv", function(error, data) {
//Doesn't work for me
data = data
}
console.log(data)
undefined
I'm trying to assign a variable to itself in a function, and if the variable has the same name as an argument to the function it doesn't seem to work, but does if they're not the same name. A code example shows this more clearly.
Is this behavior I should expect? This is a pared down example for my d3 use case which prompted this question. I've shown that below as well.
Non working example
var a;
function assign(a) {
a = a;
}
assign("test")
console.log(a)
undefined
Working Example
var a;
function assign(b) {
a = b;
}
assign("test")
console.log(a)
test
Use case
var data
d3.csv("data.csv", function(error, data) {
//Doesn't work for me
data = data
}
console.log(data)
Share Improve this question edited Jul 15, 2015 at 4:23 vinayakj 5,6813 gold badges30 silver badges49 bronze badges asked Jul 15, 2015 at 3:49 canyon289canyon289 3,5355 gold badges35 silver badges44 bronze badges 0undefined
3 Answers
Reset to default 5In your first example, the argument a
that is passed to the function shadows the variable a
which is defined outside, so: a=a
is assignment of the argument (that was passed to the function) to itself.
In Javascript the scope is functional level scope, so whenever the variable is referenced it is searched for its declaration in the containing scope(function), if it finds it it uses it else it keep searching in prototypical chain upto global scope. So in your case it tries to search a
and it founds it as argument a
so it stops the search there & uses a
from argument.
So to avoid the conflict you have use two ways.
- Use the different names
- If you want to use the same name then use the explicit scope resolution.
Ex.
var a;
function assign(a) {
Global.a = a //Global is placeholder here for outerscope that variable a is ing from.
}
assign("test")
console.log(a);
Useful links for more clear understanding
- Closures
- Variable Hoisting
you could use the window
object to access the global variable.
var a;
function assign(a) {
window.a = a; // specifying the scope.
};
assign("test")
console.log(a)
More information on 15-mon-javascript-gotchas
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745273291a4619882.html
评论列表(0条)