Js does not work in some cases when passing values by reference type

give an example


var a = function (ctx) {
    debugger // ctx {data: 555, name: 777}
    b(ctx);
    debugger; // ctx {data: 555, name: 777}
    return ctx;
}
var b = function (ctx) {
    ctx.age = 7;  //  
    ctx = ctx.data; //  ctx  555
    
    debugger; // ctx 555
}
let d = a({
    data: 555,
    name: 777
});
console.log(d); // {data: 555, name: 777, age: 777} ???  555

I"m a little confused. This is a value passed by reference type. The b function makes changes to the incoming object, and adding a age attribute works. But ctx = ctx.data; doesn"t work. I"m a little blinded.

OK, got it, because after ctx = ctx.data , I was disconnected from the original object

like



var obj = {}
obj = 123;
The

reference has been disconnected, the b function does not change the ctx object, but the variable ctx in the b function points to, and the a function still points to the original function.

May.04,2022

var a = { name: 'a' };
var b = { name: 'b' };

var c = a; //c->a
c.name = 'a change to c';
c = b; //c->b

ctx in

b is a pointer to ctx in a .

ctx.age = 7  // `ctx`
ctx = ctx.data  // 

already knows the answer,
because after ctx = ctx.data, it is disconnected from the original object

like

var obj = {}
obj = 123;
The

reference has been disconnected, the b function does not change the ctx object, but the variable ctx in the b function points to, and the a function still points to the original function.

Menu