Frage

As we know, everything is pass-by-value in JavaScript, even the Objects as function parameters are treated like a pass-by-value of the actual reference to the object.

My question is how is that possible that I have access to an Object like I can modify a property of it -- talking about objects passed to the functions as parameters, but I can not rewrite the Object itself?

Is that an intentional mechanism to avoid some errors or it's just a design-flaw or a limit? If it's intentional what is trying to achieve with that? What is the added benefit and what type of bugs/errors could happen with the ability to rewrite the object itself?

I totally understand that it is caused by pass-by-value of the object reference, however I can't figure out what is stopping me from rewriting the Object that I already have a copy of its reference -- and I can modify it as well.

Example:

var x = { arr: [1,2,3] };

var modify = function ( _x ) {
    _x.arr.push(4);
}

var rewrite = function ( _x ) {
    _x = { str: "X" };
    // OR
    _x = "X";
}

modify(x);
console.log( "X after modification: ", x );
rewrite(x);
console.log( "X after rewrite: ", x );

jsFiddle

War es hilfreich?

Lösung

while inside the modify or rewrite methods variables x and _x are references to the same object. The rewrite function changes the _x variable to point to another object. This does not change the x variable's reference which still points to the original object.

Andere Tipps

You can overwrite a reference with a different value or you can change a property of the object that is referenced.

JavaScript has no mechanism to change where a reference points to. The syntax just doesn't exist, and that is why you can't do it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top