Variable step by Javascript reference

3

I have been reading about the value and reference steps in a book, and since I am learning Javascript, I have doubts about how this can be done.

I tried the following:

var X = 10;

function cambiar(variable){
  variable++;
}

cambiar(X);
alert(X);

But, when executing the code, the variable X still has the same value, and I do not know what my error is, I searched for information, but I can not find anything very clear about it.

    
asked by Alberto Camacho 27.06.2017 в 03:14
source

2 answers

4

Javascript, does not support the passing of values by reference, at least not for variables.

Something you could do is this:

var X = 10;

function cambiar(){
  X++;
}

cambiar(X);
alert(X);

What changes with respect to your code, is the fact that now X is a global variable, the only thing we do from the change function () is the increment, it is not necessary to pass more parameters to it.

Update

There is a little trick to pass a value by reference, and it could be done like this:

var arreglo = [""];

function cambiar(variable){
  variable[0] = "FOO";
}

cambiar(arreglo);
alert(arreglo[0]);

Using an array, we can modify one of its indices, in this case the index 0 and use it later as a change of the original value.

    
answered by 27.06.2017 / 03:17
source
1

As Daniel said there is no way, the way is to pass an arrangement or object. Other ideas:

Name the variable

Problem : only works for global variables

var a=3;

function llamada(refVarGlobal){
    global[refVarGlobal]++;
}

console.log(a); // 3
llamada("a");
console.log(a); // 4

Pass name and container

Problem : can not be local. You can only pass object properties, fix positions and global

var a=3;

function llamada(contenedor, refVar){
    contenedor[refVarGlobal]++;
}

console.log(a); // 3
llamada(global, "a");
console.log(a); // 4

function ClaseMia(){
    this.b=5;
    this.incrementar = function(){
        llamada(this, "b");
    }
}

var c = new ClaseMia()

console.log(c.b); // 5
c.incrementar();
console.log(c.b); // 6

function comun(){
    var contenedor = { e: 7 };
    var arreglo = [8];
    llamada(contenedor,"e");
    llamada(arreglo,8);
}

Use a special reference object

Problem : Only variables of the Ref class can be passed as reference.

function Ref(valorInicial){
    this.valor = valorInicial;
}

function llamada(ref){
    ref.valor++;
    ref.toString = function(){
        return ref.valor;
    }
}

var a = new Ref(3);

console.log(a); // 3
llamada(a);
console.log(a); // 4
    
answered by 27.06.2017 в 03:44