javascript - How to assign a value to a variable outside a function inside a function?
淡淡烟草味
淡淡烟草味 2017-05-19 10:39:36
0
5
2612


As above, I cannot assign a new value to g. I want to write a fn function that can assign values ​​to external variables arbitrarily

The actual requirements are as above, I want to assign the instantiated variables to the outside

淡淡烟草味
淡淡烟草味

reply all(5)
PHPzhong

A concept that the questioner did not understand is the problem of how function parameters are passed.

var g = 1;
function fn(a){a=2;}
fn(g);
g//1 
//我是分割线
var g = {a:1};
function fn(b){b.a=2;}
fn(g);
g//{a:2} 

When external variables are passed into functions as parameters, you need to understand two situations, one is the basic data type and the other is the object.

When the parameters are basic data types, the parameters in the function are passed by value, that is, the value is copied to the parameter. How the function changes the parameter value is only a change to the copy of the actual parameter, which will not affect the ontology. As shown in your screenshot.

When the parameter is an object, I actually think it is a value transfer, but what is passed is the reference address value of the object. The function internally indexes the reference object address to the real data object, and then changes the attributes in the object. This It is a situation that will affect the outside world.

Generally speaking, if you want to assign a value to an external variable. You might as well not pass the variables as parameters, but do the processing directly in the function body.

var g;
function fn(){
   g = 1;
}
fn();
g//1

According to the function variable search rules, first search whether the variable has g in the current execution body. If there is no g in the outer layer, it means that the variable has not been defined or declared.

習慣沉默

Javascript’s function parameter passing is all “value passing”.

A more reasonable way to write it is

var g;
function fn() {
    return 33
}
g = fn();

Unreasonable way of writing

var g;
function fn() {
    g = 33;
}
fn();

The third reason why the latter is unreasonable is that the degree of coupling is too high.

大家讲道理
var g;
function fn(){
    g = '32';
}
fn();

This can do what you need, but you probably want a universal one, right?

你可以选择这样:
var g;
function fn(){
    return '32';
}
g = fn();
左手右手慢动作
// a 为变量名字
function fn(a){
    window[a] = '32'
}
我想大声告诉你

var g;
function fn(value){
g = value;
}
fn(1);
g//1

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!