Pass a JavaScript array to a local variable by reference?

I have a JavaScript array inside a namespace, for example:

app.collec.box = [];

and I have a function inside the same namespace:

app.init = function () {
    var box = this.collec.box;
    // ... code to modify box
};

I thought that setting a local variable equal to an object or an object was just a reference to the original, but it seems like I'm mistaken that changing the contents of a local variable boxinside my function app.collec.boxdoes not change.

Please help, what am I doing wrong? how can i solve this?

Thanks in advance.

EDIT. This is the complete code.

var app = {
    collec: {
        box: [],
        cache: []
    },

    init: function () {
        var box = this.collec.box;

        $.ajax({
            url: 'file.json',
            success: function (json) {
                // Map JSON array to box array using Underscore.js _()map
                box = _(json).map(function (o) {
                    return new Model(o);
                });
            }
        });
    }
};

app.init();
+3
source share
6 answers

, . box this.collec.box; , box this.collec.box . , .

, this.collec.box, :

this.collec.box = ...;

this.collec box:

var x = this.collec;
x.box = ...;

: , , .

box = this.collec.box, , :

this.collec.box -----> (object) <----- box

, box this.collec.box.

, , , :

box -----> this.collec.box -----> (object)

.

+6

, , .

, ( , ). , , (app.init), .

, ...

var box = this.collec.box;

... to...

var box = app.collec.box;

[EDIT]

, - : .

(var box = app.collec.box;) . , , .

+3

javascript , this app, , @rick roth. - :

var ns = this;

ns.collec.box = [];

ns , , app.init :

app.init = function () {
    var box = ns.collec.box;
    // ... code to modify box
};

, , , ns, .

+1

app.init = function (box) {
    // ... code to modify box
};

app.init(this.collec.box);
0

, app.init , . - div.onclick = app.init setTimeout (app.init, 1000), app.init, , , this app, div window .

, . :

div.onclick = function() { app.init() };

0

:

Array, . concat, join, slice? , .

:

If you are modifying a local variable box, be sure to assign it when you are done:

var box = this.collec.box;
// ... code to modify box
this.collec.box = box;
0
source

Source: https://habr.com/ru/post/1789657/


All Articles