简体   繁体   中英

Assigning a variable to itself in a function

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

在第一个示例中,传递给函数的参数a 遮盖了在外部定义的变量a ,因此: a=a是参数(传递给函数的参数)对其自身的赋值。

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.

  1. Use the different names
  2. 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 coming from.
}
assign("test")
console.log(a);

Useful links for more clear understanding

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-common-javascript-gotchas

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM