Javascript blending over variables defined by reference and value

I understand the following javascript language property:

var bar = 1;
var foo = bar;
bar = "something entirely different";
// foo is still 1

However, when you try to apply this logic to an object, it seems to act differently:

var bar = {};
bar.prop = 1;
var foo = bar;
bar.prop = "something entirely different";
// foo.prop now changes to "something entirely different"
// but...
bar = "no longer an object";
// now foo remains an object with the prop property

Can someone tell me what is happening and why there is a difference?

+5
source share
3 answers

It is right. When you assign a variable to an object, you really create a second reference to that object. In the first case, what you do is assign a barpointer to a string that foopoints to, but then you change what it points to barwhen reassigned bar.

bar , foo , bar . foo - .

: bar = "something" , bar, {} .

, . / .

+1

:

var foo = bar;

- . , foo , bar. , , bar 0xFF, foo 0xFF.

, bar foo - , .

, , bar foo, .

bar.prop = "something entirely different";  // affects foo.prop also

, :

Assignment only changes what the name of the object is bound to, and does not affect any other objects.

, , bar , foo.

bar = "no longer an object"; // Made bar hold a different memory address

, :

Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object.

:

function f(obj1, obj2)
{
    obj1.prop = 10;
    obj2 = {prop: 20};
}

var bar = {prop: 1};
var foo = {prop: 2};
f(bar, foo);
console.log("bar.prop: " + bar.prop + ", foo.prop: " + foo.prop);

: bar.prop: 10, foo.prop: 2. f, obj1 , bar, obj2 , foo. , , f , obj2 = {prop: 20}; obj2 not foo.

, the "value" is a reference to an object , , .

+1

Var .

.

, , foo bar, , , ; , .

( ) , ; foo bar, , , ; .

0

All Articles