Gzorg
Gzorg

Reputation: 857

Javascript - Set variable value inside function

I'd like to declare some variables, an then let let a function build the actual objects and assign their reference to these previously declared variables.

The way I do it now works, but it gets tedious with many variables.

function bar(obj) {
    var newObject = {'an':'object'};
    obj['element'] = newObject;
}

function foo() {
    var ref={};
    bar(ref);
    ref=ref.element; // Tedious line
}

For those wondering why I would like to do such a thing, I built a simple function to generate the DOM from JSON. It goes something like that, with #bind used to do what bar does in the previous snippet :

var legend = {};
$('#element').append(['form',['fieldset',
    ['legend',{'#bind':legend},['text':'Legend title']]
    ]].getDomForThis());
legend=legend.element;

Now I can append some new elements after the legend with something like

for(fieldName in fields) {
  legend.insertAfter(['div',[['input',['name':fieldName]],...]].getDomForThis());
}

I'd like to avoid having to write the tedious line. It's like createElement and appendChild, one function call should be enough !

UPDATE : After some thought, I believe there is no way to do that with Javascript. I was hoping for some hidden Javascript magic somewhere, but I have reason to think it will not happen.

Basically, I'd like to assign to a variable reference a new value, without creating a new reference. But a function argument a is distinct from the variable v it represents. The object pointed at are the same, but the adress of the two variables are different. Hence, assigning a new value to a cannot change the value of v in any way.

In other words, every variable has its own address, and there's not any other way to change what it points at, than referencing it explictly.

And in my case, because ref is "private" to the function, there's no way to access it from somewhere else.

Too bad...

Upvotes: 0

Views: 6249

Answers (1)

Tzury Bar Yochay
Tzury Bar Yochay

Reputation: 9004

Since there is no byRef in JavaScript, your code and the following are the same

function bar(obj) {
    return {'an':'object'};
}

function foo() {
    var obj = {};
    obj.element = bar();
}

Yet, you may do something similar to this:

function Foo() {        
    this.that = this,
    this.obj = {};
    this.bar = function () {
        var newObject = {'an':'object'};
        that.obj['element'] = newObject;
    }

    return this;
}

var f = Foo();

f.obj['foo'] = 'BAR';
f.bar();
console.log(f.obj.element.an);

Upvotes: 1

Related Questions